필터 지우기
필터 지우기

Manipulating matrix with 'for' loop

조회 수: 15 (최근 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 CenterFile Exchange에서 Direction of Arrival Estimation에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by