Manipulating matrix with 'for' loop

4 次查看(过去 30 天)
Aaron Zambiasi
Aaron Zambiasi 2020-3-1
评论: Rik 2020-3-4
Create a matrix named A of 1s with 4 columns and 6 rows. Loop the matrix and assign each element a new value using the following rules: assign 2 on the main diagonal and -1 on the adjacent diagonals.
No idea how to solve this with 'for' loop, but this is what homework quesiton asks for. Any help is much appreciated.
  2 个评论
Guillaume
Guillaume 2020-3-1
编辑:Guillaume 2020-3-1
How would you do this manually? Most likely, this would be the same method you'd use with a loop.
However, I do agree that if that's the exact wording of the assignment it's very poorly worded. For a start, 'loop the matrix' is not even proper english. Secondly, it doesn't explain what you should loop over, I assume you're expected to write a double for loop over the rows and columns, but you could also loop over the diagonals.
Of course, the proper way of doing this in matlab is without a loop, so the pedagogical aspect of that homework is questionable (in my opinion). Here's what I'd do:
for i = pi %pointless loop that only does one iteration. Only here because the assignment asks for a loop
A = toeplitz([2, -1, ones(1, 4)], [2, -1, ones(1, 2)]); %can be achieved many different ways in just one line
end
This is likely to get you a fail however even if it does produce the correct result.
Rik
Rik 2020-3-4
I would have given you bonus points for that loop. It's cheeky and shows understanding of Matlab. If I were to ask such a question I would always follow up with 'and how can you improve the performance (hint: array operations tend to be much faster)'.

请先登录,再进行评论。

回答(1 个)

Koushik Vemula
Koushik Vemula 2020-3-4
According to what I understand you want to change the values of 'main diagonal’ and ‘adjacent diagonals’ of the given matrix.
You can do it in the following manner :
A = ones(6, 4)
for i = 1:6
for j=1:4
if i==j
A(i,j) = 2;
elseif abs(i-j) == 1
A(i,j) = -1;
end
end
end
disp(A)

Community Treasure Hunt

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

Start Hunting!

Translated by