简体   繁体   中英

Creating a new vector in Matlab with the help of a for-loop

Given the vector x , I would like to create a vector u0 componentwise by checking the components of x . Since only 0 <= 0 < 1 is true, and since 0 is the first component of x , the new vector u0 should actually look like [1, 0, 0, 0, 0, 0, 0, 0] , but instead, Matlab gives me a vector that only contains 0 . What have I done wrong?

x = [0, 1, 2, 3, 4, 5, 6, 7, 8];
u0 = [];

for i = 1:8
  if (0 <= x(i) < 1)
    u0(i) = 1;
  else
    u0(i) = 0;
  end
end

Your if conditional is not correct. You need to check on it. You have to proceed like below.

x = [0, 1, 2, 3, 4, 5, 6, 7, 8];
u0 = zeros(size(x));

for i = 1:8
    if x(i) >= 0 && x(i)<1
        u0(i) = 1;
    else
        u0(i) = 0;
    end
end

Also, you can obtain the task in a single line, using the below:

u1 = zeros(size(x)) ;
u1(x>=0 & x<1) = 1 ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM