Store all results obtained from a for loop inside a matrix
1 view (last 30 days)
Show older comments
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 Comments
Accepted Answer
More Answers (1)
Samya
on 23 Jul 2023
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 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!