How to use indices in A matrix while conditonal and for loop condtion?
1 visualización (últimos 30 días)
Mostrar comentarios más antiguos
Yanni
el 17 de Mzo. de 2023
Editada: Bhanu Prakash
el 23 de Mzo. de 2023
How to use indices in LHS of A matrix while using for and if, esleif and else condtions?
clc
clear all
m=5;n=7; A=zeros(m,m);
for j=1:n
if j=1
for i=1:m,
if i==1
A(?)=i+j
elseif i==m
A(?)=i-j
else
A(?)=i
end
end
else
for i=1:m,
if i==1
A(?)=2i+j
elseif i==m
A(?)=i*j
else
A(?)=j
end
end
end
end
1 comentario
Respuesta aceptada
Bhanu Prakash
el 17 de Mzo. de 2023
Editada: Bhanu Prakash
el 23 de Mzo. de 2023
Hi Gayathri,
As per my understanding, you want to know how to index into the matrix "A" while using loops.
Please look at the following code, for your reference:
clc
clear all
A=zeros(3);
k=1;
for i=1:3
for j=1:3
A(i,j)=k;
k=k+1;
end
end
In the code shown above, the indexing is done using two indices "(i,j)", where “i” represents the row number and “j” represents the column number. The resulting matrix "A" is as follows:
A =
1 2 3
4 5 6
7 8 9
This indexing can also be done using a single index "i" in the following way:
clc
clear all
A=zeros(3);
k=1;
for i=1:9
A(i)=i;
end
The resulting matrix "A" is as follows:
A =
1 4 7
2 5 8
3 6 9
Note that, both the resulting matrices are not identical. One matrix is the transpose of the other.
You can refer to the documentation on "Array Indexing", for more info:
Hope this answer helps you.
Thanks,
Bhanu Prakash.
0 comentarios
Más respuestas (1)
Raghvi
el 17 de Mzo. de 2023
Hey Gayathri,
I have made some edits in the code to remove errors. You can use the syntax A(i,j) to access the ith row and jth column of the matrix A.
m=5;n=7;
A=zeros(n,m);
for j=1:n
if j==1
for i=1:m
if i==1
A(i,j)=i+j;
elseif i==m
A(i,j)=i-j;
else
A(i,j)=i;
end
end
else
for i=1:m
if i==1
A(i,j)=2*i+j;
elseif i==m
A(i,j)=i*j;
else
A(i,j)=j;
end
end
end
end
0 comentarios
Ver también
Categorías
Más información sobre Matrix Indexing en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!