conditional statements on matrices

Hi, I have two matrices like below:
I want to search when the 2nd column equals 0 on either matrix and make a new matrix that shows the 0 values along with its paired column 1 values. I also want to tag it to know from which matrix it came from.
Thank you! I am new to conditional statements.

 Accepted Answer

Where M1 and M2 are your matrices:
idx1 = M1(:,2) == 0;
idx2 = M2(:,2) == 0;
tags = repelem([1; 2],[nnz(idx1) nnz(idx2)]);
result = [[M1(idx1,:); M2(idx2,:)] tags]

9 Comments

Voss, you've done it again. I appreciate the simple solution and was over thinking it by thinking I had to use conditional statements/loops.
Many thanks!
You're welcome!
Hi Voss, I'm getting a larger matrix than desired for some reason. The matrix length of 0s for M1 is 47,582 and M2 433,660 so combined should have a 909,552 by 3 matrix but I'm getting 141,648 by 3 matrix.
Any suggestions?
Save M1 and M2 in a mat file and upload it here using the paperclip button.
load M1
load M2
whos M*
Name Size Bytes Class Attributes M1 525600x2 8409600 double M2 525600x2 8409600 double
I'm not sure why you say "the matrix length of 0s for M1 is 47,582 [475,892?] and M2 433,660". How are you determining that?
I get 49,708 zeros in the second column of M1 and 91,940 zeros in the second column of M2:
idx1 = M1(:,2) == 0;
idx2 = M2(:,2) == 0;
nnz(idx1)
ans = 49708
nnz(idx2)
ans = 91940
49708+91940 = 141648, exactly the size of the result you get.
thats interesting, if I do
x = nnz(idx2);
from your code I also get 91940 but if I do
x = nnz(M2(:,2));
I get 433660
** I am guessing what I did was incorrect/invalid?
You're basically counting the opposite of what you want. (Notice that 433660 (your count) + 91940 (my count) = 525600 (the total number of elements in M(:,2).)
This
nnz(M2(:,2))
gives you the number of non-zero elements in column 2 of M2. (nnz means number of non-zero elements.)
But you want to count the number of zero elements, which is
idx2 = M2(:,2) == 0;
nnz(idx2)
or
nnz(M2(:,2) == 0)
because idx2 (or M2(:,2) == 0) is a logical vector that is true where M(:,2) is zero and false where M(:,2) is non-zero. In a logical array, false is considered zero and true is non-zero. So nnz(idx2) is the number of non-zero elements in idx2, which is the number of elements where idx2 is true, which is the number of elements where M(:,2) is zero.
oh my gosh! *face palm*
Thank you! I'm sorry for the run around!
No problem! You're welcome!

Sign in to comment.

More Answers (0)

Categories

Asked:

on 8 Apr 2024

Commented:

on 8 Apr 2024

Community Treasure Hunt

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

Start Hunting!