How can I make a square matrix with a nested for loop?
Show older comments
Hi, I need to make a square matrix using a nested for loop.The matrix is as below:-
1 2 4 8
2 1 2 4
4 2 1 4
8 4 2 1
To explain the above the diagonals are all 1, the adjacent values to the diagonal are increasing in the power on either side. I used the below loop structure. However, I am not getting any answer for the below.
si=zeros(4,4);
for i = 0:4,
for j = 0:4,
if(i==j)
si(i,j) = 1;
elseif(j>i)
si(i,j) = 2^abs(i-j);
elseif(i>j)
si(i,j) = 2^abs(i-j);
end
end
Kindly help!
1 Comment
Answers (3)
Walter Roberson
on 7 Feb 2017
1 vote
Heh. I saw that KSSV had posted a perfectly valid explanation so I deleted mine (he was first), and it looks like KSSV saw that I posted an explanation and so decided to delete his own.
Anyhow:
Your loops should start at 1, not at 0.
You are missing an 'end' for your 'if'
2 Comments
Guillaume
on 7 Feb 2017
... and considering that both elseif do the same thing, they could just be merge it a simple else.
Guillaume
on 7 Feb 2017
The best way to create that matrix is not to use a loop, but simply:
sidelength = 4;
si = toeplitz(2.^(0:sidelength-1))
2 Comments
Stephen23
on 7 Feb 2017
+1 good use of MATLAB.
Or:
si = 2 .^ abs((1:4) - (1:4).') % Matlat >= 2016b
or with older Matlab versions:
si = 2 .^ abs(bsxfun(@minus, 1:4, (1:4).'))
Azmat Rasool
on 18 Mar 2021
0 votes
How we create indentity matrix of order 3*5 with the help of nested for loop
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!