Check if matrix contains zero or not and ...

89 Ansichten (letzte 30 Tage)
Lizan
Lizan am 14 Nov. 2012
Bearbeitet: Moshe Flam am 27 Dez. 2017
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 Kommentar
Jan
Jan am 14 Nov. 2012
What have you tried so far and which problems occurred?

Melden Sie sich an, um zu kommentieren.

Antworten (2)

Jürgen
Jürgen am 14 Nov. 2012

Moshe Flam
Moshe Flam am 26 Dez. 2017
Bearbeitet: Moshe Flam am 27 Dez. 2017
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;

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by