MATLAB: Reproduce the matrix shown below by using nested loops and a if…elseif…else…end statement

else statementelseif statementhomeworkif statementmatrixnested loops

8 3 0 0 0
6 8 3 0 0
0 6 8 3 0
0 0 6 8 3
0 0 0 6 8
This is my current code and its quite frankly a mess, I don't even understand it myself. It doesn't produce an output.
clear;
x=zeros(5,5);
for r=1:5;
for c=1:5;
if x(r)==c;
disp(8);
elseif x(r)== c+1;
disp(3);
elseif x(r)==c-1;
disp(6);
else
disp(0);
end;
fprintf('\n');
end;
Can I get a bit of assistance please.

Best Answer

Again, you’re close. You have to reference ‘x’ by both its rows and columns this time. Your idea was correct in testing for row and column equality, but you need to test ‘r’ against ‘c’, not ‘x’ against ‘c’, so that was all I changed in the if blocks. (You also switched the ‘6’ and ‘3’ assignments, so I corrected that. You would have discovered it quickly enough.) You already know how to print the rows of ‘x’, so I’ll leave that to you.
x=zeros(5,5);
for r=1:5;
for c=1:5;
if r==c;
x(r,c) = 8;
elseif r == c+1;
x(r,c) = 6;
elseif r==c-1;
x(r,c) = 3;
else
x(r,c) = 0;
end;
fprintf('\n');
end
end