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 个评论

Please mention, if this is a homework question or not, because then a different kind of answering is required.

请先登录,再进行评论。

回答(3 个)

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 个评论

... and considering that both elseif do the same thing, they could just be merge it a simple else.
You do not even need to exclude the case i==j, because 2^(abs(i-j)) replies 1 as wanted already. So omit the IF block.

请先登录,再进行评论。

The best way to create that matrix is not to use a loop, but simply:
sidelength = 4;
si = toeplitz(2.^(0:sidelength-1))

2 个评论

Or:
si = 2 .^ abs((1:4) - (1:4).') % Matlat >= 2016b
or with older Matlab versions:
si = 2 .^ abs(bsxfun(@minus, 1:4, (1:4).'))

请先登录,再进行评论。

How we create indentity matrix of order 3*5 with the help of nested for loop

类别

在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

提问:

Ash
2017-2-7

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by