How to connect logical operation using for loop?
3 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Jiahong Zou
am 13 Jul. 2023
Beantwortet: Vishnu
am 13 Jul. 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 Kommentare
Akzeptierte Antwort
Vishnu
am 13 Jul. 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 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Mathematics and Optimization finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!