user1362166
user1362166

Reputation:

How to create an array in Matlab but run a function at the same time?

I'm trying to populate an array with values from a function that I am running. In this function I am changing a variable z2 in increments of 0.01 from 0 to 0.99. At the same time I want to populate an array with those values. I've tried a while loop and a for loop. How to write this with only a for loop?

my code:

Ys = y(2000);
Mp = ((max(y)-Ys)/Ys)*100;
[max, i] = max(y);
tp = t(i);
z = sqrt(((log(Mp))^2)/((pi*pi)+(log(Mp))^2));


%Given Equations
wd = pi/tp;
wn = wd/(sqrt(1-(z*z)));
ts = 4.6/(z*wn);
tr = 1.8/wn;

%for loop for z from 0 to 0.99
for i = 1:100;
   for z2 = 0:0.01:0.99
      %tr*wn = Fa
      Fa(i) = 2.917*z2^2 - 0.4167*z2 + 1;
      i = i + 1;
      if i >= 100;
          break;
      end
    end
end

find_zeta = interp1(Fa, 1.8);

disp(Fa);
disp(find_zeta);

error I am experiencing: I am getting only 1s in my array.

Upvotes: 2

Views: 208

Answers (2)

angainor
angainor

Reputation: 11810

You can do it without a loop, in a 'vectorized' matlab statement

z2 = 0:0.01:0.99;
Fa = 2.917*z2.^2 - 0.4167.*z2 + 1;

First, compute z2 values that you need. Next, operating on the vector element by element (note .^ syntax) compute Fa. There is a fundamental difference between ^ and .^ operators, and you really want to know the difference. In general, you can add a . to an operator, which means that it will work on individual scalar elements of your array. Read about matrix and array operators here. For example:

A = rand(10);
B = rand(10);
% matrix multiplication
C=A*B; 
% element by element multiplication
C=A.*B

The complaint you got only means that what you do is inefficient. Since matlab does not know the size of Fa beforehand, it needs to reallocate the array every time you append to it. You can still use it, it is just inefficient.

Upvotes: 4

didster
didster

Reputation: 882

Index's in matlab start from 1, not from 0 as they do in other programming languages

The error you are getting is about pre-allocating the array. Add Fa = zeros(1,100); to the start of the script and it will go away.

Fa = zeros(1,100);
i = 1;
for z2 = 0:0.01:0.99
   Fa(i) = 2.917*z2^2 - 0.4167*z2 + 1;
   i = i +1;
end

The use of 'vectorized' as suggested in another answer is more the way to go though.

Upvotes: 1

Related Questions