How can I make a square matrix with a nested for loop?
显示 更早的评论
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 个评论
回答(3 个)
Walter Roberson
2017-2-7
1 个投票
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 个评论
Guillaume
2017-2-7
... and considering that both elseif do the same thing, they could just be merge it a simple else.
Guillaume
2017-2-7
The best way to create that matrix is not to use a loop, but simply:
sidelength = 4;
si = toeplitz(2.^(0:sidelength-1))
2 个评论
Stephen23
2017-2-7
+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
2021-3-18
0 个投票
How we create indentity matrix of order 3*5 with the help of nested for loop
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!