3

I am new to MATLAB and I want to write a simple program to generate an n x n matrix A such that:
1. a11 = 2
2. a22 = ... = ann = 5
3. 0 everywhere else

Can the program take n as an argument? So that I will have to choose an n every time I run the program.

Thanks!

1
  • Is this a homework assignment? Commented Jun 22, 2011 at 1:39

2 Answers 2

5
n = 8;             %# input value, matrix size

A = 5.*eye(n);     %# put 5 on diagonal, zeros elsewhere
A(1,1) = 2;        %# first element
3

Here's another way of doing the same.

n=8;
A=diag([2 5*ones(1,n-1)]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.