Filter löschen
Filter löschen

How to use indices in A matrix while conditonal and for loop condtion?

2 Ansichten (letzte 30 Tage)
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

Akzeptierte Antwort

Bhanu Prakash
Bhanu Prakash am 17 Mär. 2023
Bearbeitet: Bhanu Prakash am 23 Mär. 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.

Weitere Antworten (1)

Raghvi
Raghvi am 17 Mär. 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

Kategorien

Mehr zu Matrix Indexing finden Sie in Help Center und File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by