user11060735
user11060735

Reputation:

Using an if statement to fill a matrix

I have a .csv file which includes two columns and each column has a matrix of size 68x1. In order to read the file I use this code:

filename1= 'myfile.csv';
[d1,tex]= xlsread(filename1);
b=d1(:,1);

I would like to take some values using if. I have written :

if b<=4.5&&b<60
    X=2*b+5
elseif b>=60
    X=3*b-6
end

However, it doesn't work. How can I do this?

Upvotes: 1

Views: 106

Answers (1)

Wolfie
Wolfie

Reputation: 30047

In your example, b is a vector. The statement b <= 4.5 outputs a logical vector, which can't be used with the short-circuit double ampersand && and another logical vector.

I'm also going to assume you had a typo, because b<60 is always true if b<=4.5, I think you meant b>=4.5.

You have two options:

  1. Put this in a loop

    for ii = 1:numel(b)
        if b(ii) >= 4.5 && b(ii) < 60
            X(ii) = 2*b(ii) + 5;
        elseif b >= 60
            X(ii) = 3*b(ii) - 6;
        end
    end
    
  2. The more MATLAB-esque way would be to take advantage of vectorisation, note the single ampersand &:

    X = NaN( size(b) );
    X( b >= 4.5 & b < 60 ) = 2*b + 5;
    X( b >= 60 ) = 3*b - 6; 
    

Upvotes: 3

Related Questions