How to connect logical operation using for loop?

3 views (last 30 days)
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 ?

Accepted Answer

Vishnu
Vishnu on 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
row = 2×1
1 3
col = 2×1
1 1
row_constant = 2×1
1 3
col_constant = 2×1
1 2
row = 2×1
1 2
col = 2×1
2 2
row_var = 2×1
1 2
col_var = 2×1
1 2

More Answers (0)

Categories

Find more on Mathematics and Optimization in Help Center and File Exchange

Products


Release

R2022b

Community Treasure Hunt

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

Start Hunting!