Store all results obtained from a for loop inside a matrix

조회 수: 1 (최근 30일)
Alberto Acri
Alberto Acri 2023년 7월 23일
편집: Stephen23 2023년 7월 23일
Hi. I need to transform the matrix 'matrix' to 'matrix_out' by inserting the number '0' inside the matrix 'matrix' in reference to the coordinates of the matrix 'coord'.
I tried this for loop and it works, but I don't understand how to return all the results of the for loop to the matrix matrix_out.
matrix = [5,6,14,25; 14,55,44,16; 98,65,34,75; 67,89,21,88];
coord = [1,1; 1,3; 2,2; 3,2; 4,3; 4,4];
for K = 1:length(coord)
A = coord(K,:);
A_x = A(1);
A_y = A(2);
matrix_out = matrix;
matrix_out(A_x,A_y) = 0;
end
% RESULT: matrix_out = [0,6,0,25; 14,0,44,16; 98,0,34,75; 67,89,0,0];

채택된 답변

Stephen23
Stephen23 2023년 7월 23일
편집: Stephen23 2023년 7월 23일
The simpler MATLAB approach is to use SUB2IND:
matrix = [5,6,14,25; 14,55,44,16; 98,65,34,75; 67,89,21,88];
coord = [1,1; 1,3; 2,2; 3,2; 4,3; 4,4];
idx = sub2ind(size(matrix),coord(:,1),coord(:,2));
matrix(idx) = 0
matrix = 4×4
0 6 0 25 14 0 44 16 98 0 34 75 67 89 0 0

추가 답변 (1개)

Samya
Samya 2023년 7월 23일
Hi, from my understanding there is a very minor change in your code,
To achieve the desired result, you need to initialize the `matrix_out` variable before the loop and update it within the loop. Here's the modified code:
matrix = [5,6,14,25; 14,55,44,16; 98,65,34,75; 67,89,21,88];
coord = [1,1; 1,3; 2,2; 3,2; 4,3; 4,4];
matrix_out = matrix; % Initialize matrix_out with the original matrix
for K = 1:length(coord)
A = coord(K,:);
A_x = A(1);
A_y = A(2);
matrix_out(A_x,A_y) = 0; % Update matrix_out with the value 0 at the specified coordinates
end
matrix_out
matrix_out = 4×4
0 6 0 25 14 0 44 16 98 0 34 75 67 89 0 0
By initializing `matrix_out` with `matrix` outside the loop, you ensure that it starts with the same values as `matrix`. Then, within the loop, you update the corresponding coordinates in `matrix_out` with the value `0`.
Hope this helps!

카테고리

Help CenterFile Exchange에서 Multidimensional Arrays에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by