Store all results obtained from a for loop inside a matrix
1 次查看(过去 30 天)
显示 更早的评论
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];
0 个评论
采纳的回答
更多回答(1 个)
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
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!
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Multidimensional Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!