Filter löschen
Filter löschen

Manipulating matrix with 'for' loop

16 Ansichten (letzte 30 Tage)
Aaron Zambiasi
Aaron Zambiasi am 1 Mär. 2020
Kommentiert: Rik am 4 Mär. 2020
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 Kommentare
Guillaume
Guillaume am 1 Mär. 2020
Bearbeitet: Guillaume am 1 Mär. 2020
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 am 4 Mär. 2020
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)'.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Koushik Vemula
Koushik Vemula am 4 Mär. 2020
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)

Kategorien

Mehr zu Loops and Conditional Statements 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