필터 지우기
필터 지우기

How to connect logical operation using for loop?

조회 수: 2 (최근 30일)
Jiahong Zou
Jiahong Zou 2023년 7월 13일
답변: Vishnu 2023년 7월 13일
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 ?

채택된 답변

Vishnu
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
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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품


릴리스

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by