Simplicity
Simplicity

Reputation: 48966

Returning all the values in the array

For the following function in matlab:

function s = support(x, y)
for i=1:length(x)
if(y(i)~=1)
s = x(i);
end
end
end

I was intending to return all the values that meet the if-statement, but seems that the function only returns the last element that satisfies the `if-statement. How can I return all the values? What modification should I apply?

Upvotes: 0

Views: 64

Answers (3)

memyself
memyself

Reputation: 12638

use logical indexing to return all elements in x that satisfy the condition y not 1:

s = x( y ~= 1)

Upvotes: 0

Ninjasam
Ninjasam

Reputation: 101

Your s value is not an array so you return only the last value

function s = support(x, y)
j=1;
for i=1:length(x)
  if(y(i)~=1)
    s(j) = x(i);
    j=j+1;
  end
end

Note also that for this kind of problem there is a lot of syntax shorcuts in Matlab which are very more efficient and this is the power of Matlab. You could just write:

function s = support(x, y)
s=x(y~=1);

(Look at logical indexing to understand)

Upvotes: 2

Jonas
Jonas

Reputation: 74940

You can simply write

s = x(y~=1)

This will return all elements in x that satisfy your condition (y~=1). However, if s should be the same size as x and y, then it may make more sense to mask the elements in s where the condition is false, i.e.

s = x;
s(y==1) = NaN

Upvotes: 2

Related Questions