MATLAB: Verify the For Loops

for loophomework

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

Best Answer

The reason you are getting all 7's in your answer is because i+j is always 7, so you are assigning 7 to each element. And the indexing is not correct for your second and third parts.
For the double for loop, you need to make the (k,z) element depend on the variables k and z which are used for the loop indexes, not i and j which are not used for the loop indexes. E.g.,
A(k,z) = k + z;
Had you used i and j for the loop indexes, then you could have used i + j in the above line.
For the building by row part, you need the assignment to be this for the k'th row:
A(k,:) = SOMETHING; % <-- You need to figure out how to fill in the SOMETHING

For the building by column part, you need the assignment to be this for the z'th column:
A(:,z) = SOMETHING; % <-- You need to figure out how to fill in the SOMETHING
So, I have fixed the first part for you, and partially fixed the second and third parts. You just need to figure out how to make a row of the appropriated numbers for the second part, and how to make a column of the appropriate numbers for the third part.