How to connect logical operation using for loop?
3 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Vishnu
2023-7-13
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!