How to use indices in A matrix while conditonal and for loop condtion?
1 次查看(过去 30 天)
显示 更早的评论
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
采纳的回答
Bhanu Prakash
2023-3-17
编辑:Bhanu Prakash
2023-3-23
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 个评论
更多回答(1 个)
Raghvi
2023-3-17
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!