Scavenger23
Scavenger23

Reputation: 209

How to run a for loop using two variables at the same time in Matlab

I am using this command in Matlab:

grazAng = grazingang(H,R)

If i fix H, I can treat R as a vector:

z=[];
for i=1:1000
z(i)=abs(grazingang(1,i));
end

Now I would like to have both H and R to by dynamic. For example:

H=[0,0.25,0.5]
R=[1,2,3]

And I would like my loop to run three times, each time selecting a pair of (H,R) values with the same indexes, i.e. (0,1),(0.25,2),(0.5,3) and then store the result in z. Could anyone help me out with this?

Upvotes: 1

Views: 76

Answers (1)

Jeremy Hughes
Jeremy Hughes

Reputation: 103

Remember, everything in MATLAB is an array. To do this with a loop, you need to index into the arrays:

H = [0,0.25,0.5];
R = [1,2,3];

z = zeros(size(H)); % Pre-allocation is generally advised
for i = 1:1000
    z(i) = abs(grazingang(H(i),R(i)));
end

But MATLAB functions generally accept vectors and do this for you, so all you need to do is:

H=[0,0.25,0.5];
R=[1,2,3];
z = abs(grazingang(H,R));

Upvotes: 2

Related Questions