Store all results obtained from a for loop inside a matrix

1 visualizzazione (ultimi 30 giorni)
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];

Risposta accettata

Stephen23
Stephen23 il 23 Lug 2023
Modificato: Stephen23 il 23 Lug 2023
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

Più risposte (1)

Samya
Samya il 23 Lug 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
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!

Categorie

Scopri di più su Multidimensional Arrays in Help Center e File Exchange

Prodotti


Release

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by