How to connect logical operation using for loop?
3 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Jiahong Zou
le 13 Juil 2023
Réponse apportée : Vishnu
le 13 Juil 2023
I have 50 matrices of same dimension, in which some nonzero elements that are same among all matrices and some could have different values. Now i want to get the indices of constant elements and indices of variable elements. If there are only 2 matrices the problem would be solved easily by
cell = {} % cell matrix containing matrices
cell{1} = [1 2 0; 0 1 0; 5 0 0];
cell{2} = [1 3 0; 0 4 0; 5 0 6];
[row_constant,col_constant] = find(cell{1}==cell{2} & cell{1}~=0)
[row_var,col_var] = find(cell{1}~=cell{2} & cell{1}~=0 & cell{2}~=0)
I cant repeatedly write A==B & B==C & .... forever and the number of matrices are also not always the same.
What should i do ?
0 commentaires
Réponse acceptée
Vishnu
le 13 Juil 2023
To solve the problem for an arbitrary number of matrices, you can use a loop in MATLAB. Here's an example code snippet that you can use:
% cell matrix containing matrices
cell{1} = [1 2 0; 0 1 0; 5 0 0];
cell{2} = [1 3 0; 0 4 0; 5 0 6];
num_matrices = numel(cell); % Get the number of matrices
% Initialize variables to store the indices of constant and variable elements
[row_constant, col_constant] = find(cell{1} ~= 0); % Start with non-zero elements of the first matrix
[row_var, col_var] = deal([]); % Empty arrays
% Loop through the remaining matrices
for i = 2:num_matrices
% Find the indices of constant elements
[row, col] = find(cell{1} == cell{i} & cell{1} ~= 0)
% Update the indices of constant elements
[row_constant, col_constant] = intersect(row_constant, row, 'rows', 'stable')
% Find the indices of variable elements
[row, col] = find(cell{1} ~= cell{i} & cell{1} ~= 0 & cell{i} ~= 0)
% Update the indices of variable elements
[row_var, col_var] = unique([row_var; row], 'rows', 'stable')
end
0 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Mathematics and Optimization dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!