Check if matrix contains zero or not and ...

조회 수: 274(최근 30일)
Lizan
Lizan 2012년 11월 14일
편집: Moshe Flam 2017년 12월 27일
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...
  댓글 수: 1
Jan
Jan 2012년 11월 14일
What have you tried so far and which problems occurred?

댓글을 달려면 로그인하십시오.

답변(2개)

Jürgen
Jürgen 2012년 11월 14일
  댓글 수: 1
Moshe Flam
Moshe Flam 2017년 12월 26일
link is broken

댓글을 달려면 로그인하십시오.


Moshe Flam
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;

범주

Find more on Creating and Concatenating Matrices in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by