How can I make a square matrix with a nested for loop?
Mostrar comentarios más antiguos
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 comentario
Respuestas (3)
Walter Roberson
el 7 de Feb. de 2017
1 voto
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 comentarios
Guillaume
el 7 de Feb. de 2017
... and considering that both elseif do the same thing, they could just be merge it a simple else.
Guillaume
el 7 de Feb. de 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 comentarios
Stephen23
el 7 de Feb. de 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
el 18 de Mzo. de 2021
0 votos
How we create indentity matrix of order 3*5 with the help of nested for loop
Categorías
Más información sobre Loops and Conditional Statements en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!