0

How to save values of x for condition below and assign y to them to find its length

    for i=1:100
    n=1;
    x(i)=rand
    if x>0.5
    y=x;
    end
    length(y)
    end
Rokki balboa
  • 23
  • 1
  • 5

1 Answers1

1

You don't need a loop here. Do the following:

x = rand(1,100); %Storing all values at once
y = x(x>0.5);    %Storing values of x greater than 0.5 in y
length(y)        %Finding the length of y

Suggested reading:
‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ ‍‍‍‍‍‍ Matrix Indexing in MATLAB
by Steve Eddins and Loren Shure (MathWorks)

Sardar Usama
  • 19,536
  • 9
  • 36
  • 58
  • Apart from that, always avoid using `i` and `j` as variables names. Read more here: http://stackoverflow.com/questions/14790740/using-i-and-j-as-variables-in-matlab – Sardar Usama Feb 18 '17 at 17:22