Check if matrix contains zero or not and ...
조회 수: 51 (최근 30일)
이전 댓글 표시
Hi,
I want to check if matrix contains zero or not, and if its zero in a specific column that I pick.. say the first one, then I want to add the last value in that column to the zero ones.
How on earth do I do this in a effective and fast way?
Many thanks...
답변 (2개)
Moshe Flam
2017년 12월 26일
편집: Moshe Flam
2017년 12월 27일
Here's the short answer: Explained further.
C = M{:,find(sum(M == 0))}; % C are the zero cols indice
Z = M(:,C) == 0; % Z is an indicator matrix
% marking zeros
% only in columns with zeros
N = M; % leaving M intact. Creating copy
N{:,C} = diag(M(end,C)) * Z;
% M(end,C) are the last val of the columns with zeros
% for last non-zero vals, see remark*
_______________________
Detailed Explanation:
To find the zeroes in a column of the matrix M
colidx = 1; % first column
col = M(:,colidx);
idx = col == 0;
To check if it has zeroes, sum up the result and check it is over zero
hasZeros = sum(idx(:)) > 0;
So lets work with a matrix, and get the colidxs that have zero:
zeros = M == 0; % indicator: 1 where there's a zero
sums = sum(zeros); % sum per column
colidxs = find(sums); % indice of columns with zeros
zeroCols = M(:,colidxs); % data of columns with zeros
zerosOnly = zeros(:,colidxs); % indicator only for cols with zero
lastvals = zeroCols(end,:);
We now do a matrix multiplication with the diagonal:
i.e. for the following:
M = [1, 2, 3, 4;...
11, 22, 0, 44;...
111, 0, 333, 444;...
10, 20, 30, 40];
colIdxs: 2,3
lastvals: 20,30
zeroCols: 0,0
0,1
1,0
0,0
matrix multiply diagonal
x 20, 0
0, 30
gives: 0,0; 20,0; 0,30; 0,0
Finally, add the result to the data cols using matrix multiplication:
So:
valsmat = zeroCols * diag(lastvals); % vals matrix
result = M; % copy of M, leaving M intact
result{:,colidxs} = M:{:,colidxs} + valsmat; % add the vals matrix
Resulting in:
M = [ 1, 2, 3, 4;...
11, 22, 30, 44;...
111, 20, 333, 444;...
10, 20, 30, 40];
______
() *Remark:
If you don't want the last value, but rather the last non-zero value of the column, you'll need to create a vector of last values.
So:
% lastvars = to-be-completed
N{:,C} = diag(lastvars) * Z;
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!