beginh
beginh

Reputation: 1153

iterate over matrices in matlab

I have following problem:

I delete entries when in both matrices they are zero. If I have i pairs of such matrices, how to properly write indexing for the loop in matlab here? code:

x = [0 0 0 1 1 0 5 0 7 0]
y = [0 2 0 1 1 2 5 2 7 0]

idx = ~(x==0 & y==0);

x2 = x(idx)
y2 = y(idx)

can you help me?

Upvotes: 1

Views: 300

Answers (2)

Thor
Thor

Reputation: 47249

If I understand you correctly, you want to match elements where both x and y are zero, so something like this should work (without the not ~):

idx = (x==0 & y==0);

x2 = x(~idx)
y2 = y(~idx)

Edit

Or more simply, as suggested by mutzmatron:

idx = (x ~= 0 | y ~= 0);

x2 = x(idx)
y2 = y(idx)

Upvotes: 1

High Performance Mark
High Performance Mark

Reputation: 78374

Like this perhaps ?

x2 = x(find(or((x~=0),(y~=0))))
y2 = y(find(or((x~=0),(y~=0))))

These, obviously, don't do an in-place replacement, so x and y are not changed. I haven't figured out how to do that on both arrays simultaneously yet.

EDIT Read @mutzmatron's comments below

Upvotes: 0

Related Questions