Verify my For Loops
Show older comments
Hey guys! I am still kind of getting a hang of Matlab and I have a quick favor to ask you guys. The question is to create a double for loop for the following 3 × 4 matrix with ijth matrix element: A(i,j)=i+j, 1≤i≤3, 1≤j≤4 Construct this matrix in MATLAB using the following four methods: a. Using a double for-loop. b. Using a for-loop that builds the matrix row by row. c. Using a for-loop that builds the matrix column by column.
I have already done this but I am getting sort of an odd answer, would someone please verify my work?
i=3;
j=4;
A=zeros(i,j);
for k=1:i,
for z=1:j
A(k,z)=i+j;
end
end
A
%Part B
for k=1:i
A(k)=i+j;
end
A
%Part C
for z=1:j
A(z)=i+j;
end
A
oh and this are the arrays I got:
A =
7 7 7 7
7 7 7 7
7 7 7 7
A =
7 7 7 7
7 7 7 7
7 7 7 7
A =
7 7 7 7
7 7 7 7
7 7 7 7
Accepted Answer
More Answers (1)
John BG
on 9 Dec 2015
N=3
M=4
A=zeros(N,M)
for i=1:1:N
for j=1:1:M
A(i,j)=i+j
end
end
N=3
M=4
A=zeros(N,M)
j=1
while j<M+1
for i=1:1:N
A(i,j)=i+j
end
j=j+1
end
N=3
M=4
A=zeros(N,M)
i=1
while i<N+1
for j=1:1:M
A(i,j)=i+j
end
i=i+1
end
And the MATLAB way would be:
N=3;M=4;A=zeros(N,M)
[I,J]=ind2sub(size(A),find(A==0))
A=I+J
reshape(A,N,M)
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!