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)

カテゴリ

Help Center および File ExchangeDirection of Arrival Estimation についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by