Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

for loops and loss of data

0 views
Skip to first unread message

bacterial

unread,
Nov 24, 2009, 12:14:19 AM11/24/09
to
Hi
I'm relatively new to Matlab and still a bit unsure what im doing.
Ive made a for loop for which a bunch of 100x1 matrices are split into 100 1x1 matrices and functions are performed on them.
Then after the loop, I want to get the values back into a 100x1 matrix...
any ideas?

heres my input, if it makes sense:
n=input('number of particles:');
a=input('sample area size:');
x=1+(a-1).*rand(n,1);
y=1+(a-1).*rand(n,1);
u=-a+(a-(-a)).*rand(n,1);
v=-a+(a-(-a)).*rand(n,1);
quiver(x,y,u,v);
u2=mat2cell(u,ones(n,1),1);
v2=mat2cell(v,ones(n,1),1);
for p=1:n
v3=v2{p,1};
u3=u2{p,1};
b=v3/u3;
T1=atand(b);
end
for p=1:n
v3=v2{p,1};
u3=u2{p,1};
l=sqrt((u3^2)+(v3^2));
end


Thanks for your help :)

Jan Simon

unread,
Nov 24, 2009, 3:49:20 AM11/24/09
to
Dear bacterial!

> Ive made a for loop for which a bunch of 100x1 matrices are split into 100 1x1 matrices and functions are performed on them.
> Then after the loop, I want to get the values back into a 100x1 matrix...
> any ideas?
>
> heres my input, if it makes sense:
> n=input('number of particles:');
> a=input('sample area size:');
> x=1+(a-1).*rand(n,1);
> y=1+(a-1).*rand(n,1);
> u=-a+(a-(-a)).*rand(n,1);
> v=-a+(a-(-a)).*rand(n,1);
> quiver(x,y,u,v);
> u2=mat2cell(u,ones(n,1),1);
> v2=mat2cell(v,ones(n,1),1);
> for p=1:n
> v3=v2{p,1};
> u3=u2{p,1};
> b=v3/u3;
> T1=atand(b);
> end
> for p=1:n
> v3=v2{p,1};
> u3=u2{p,1};
> l=sqrt((u3^2)+(v3^2));
> end

As far as I see in this example, the conversion to cells is not needed.Which values do you want to get backto 100x1 vectors? I assume you want [T1] and [l]:

n = input('number of particles:');
a = input('sample area size:');
x = 1+(a-1).*rand(n,1);
y = 1+(a-1).*rand(n,1);
u = -a+(a-(-a)).*rand(n,1);
v = -a+(a-(-a)).*rand(n,1);
quiver(x,y,u,v);
T1 = zeros(n, 1);
L = zeros(n, 1); % Uppercase L is less confusing
for p=1:n
v3 = v(p);
u3 = u(p);
b = v3 / u3;
T1(p) = atand(b);
end
for p = 1:n
v3 = v2(p);
u3 = u2(p);
L(p) = sqrt((u3^2)+(v3^2));
end

But finally you can calculate T1 and L much faster with vectorization - without FOR loops:
T1 = atand(v ./ u); % but atand must accepot vectors...
L = sqrt(u.*u + v.*v); % SQRT accepts vectors!

Kind regards, Jan

bacterial

unread,
Nov 24, 2009, 5:49:03 PM11/24/09
to
That was fantastic!! Thanks Jan :)
I'll give vectorisation a squiz, it looks to be very useful. Matlab is SWEEET!!
cheers,
Lisa
0 new messages