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
1 件のコメント
採用された回答
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!