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!