Collect values into an array
Show older comments
I have the following within my code :
while time<tfinal
for np = 1 : particleno
%Run Function to calculate guiding centre for diagnostic test
[a, b, gcx]=guidingcentrefun(x1(np), x2(np), x3(np), y1(np), y2(np), y3(np));
end
end
Where guidingcentrefun is as follows:
function [ a b gcx] = guidingcentrefun(x1, x2, x3, y1, y2, y3)
%Calculate guiding centre with simultaneous eqns
k1=(-2*x1)+(2*x2);
k2=(-2*y1)+(2*y2);
k3=(x2^2) -(x1^2) + (y2^2) - (y1^2);
k4=(-2*x1)+(2*x3);
k5=(-2*y1)+(2*y3);
k6=(x3^2)-(x1^2)+(y3^2)-(y1^2);
%coordinates of guiding centre
b=((k1*k6)-(k3*k4))/((k1*k5)-(k2*k4));
a=(k3-(k2*b))/k1;
gcx = [ a ];
end
I just want gcx to store ALL of the values of a in one array. I can run the code and let the values of gcx be outputted so I know it all works:
gcx =1.1139
gcx =1.1146
gcx =1.1153
gcx =1.1159
gcx =1.1165
gcx =1.1170
gcx =1.1175
I know this is probably quite simple but i cant get it right and it is pretty urgent so help would be so much appreciated!! please! Thanks in advance! Phoebe
3 Comments
Phoebe
on 28 Mar 2014
Image Analyst
on 28 Mar 2014
Then why does np go from 1 to particleno? Also, there is no time compute in the loop. I'll try your code attached below but I need to go out for a few hours. Post back if you end up fixing it on your own.
Phoebe
on 28 Mar 2014
Answers (1)
Image Analyst
on 28 Mar 2014
Try
for np = 1 : particleno
%Run Function to calculate guiding centre for diagnostic test
[a, b, gcx(np)]=guidingcentrefun(x1(np), x2(np), x3(np), y1(np), y2(np), y3(np));
end
where you're adding an index, np, to the variable. The gcx in the main program is a separate variable from that in the called function, so it's okay to do it like this.
4 Comments
Phoebe
on 28 Mar 2014
Image Analyst
on 28 Mar 2014
Seems strange. It worked fine for me. Try my exact code (save it in a file called "test2.m"):
function test2
particleno = 10;
% Sample data:
x1 = rand(1,particleno);
x2 = rand(1,particleno);
x3 = rand(1,particleno);
y1 = rand(1,particleno);
y2 = rand(1,particleno);
y3 = rand(1,particleno);
for np = 1 : particleno
%Run Function to calculate guiding centre for diagnostic test
[a, b, gcx(np)] = guidingcentrefun(x1(np), x2(np), x3(np), y1(np), y2(np), y3(np))
end
plot(gcx);
function [a, b, gcx] = guidingcentrefun(x1, x2, x3, y1, y2, y3)
%Calculate guiding centre with simultaneous eqns
k1=(-2*x1)+(2*x2);
k2=(-2*y1)+(2*y2);
k3=(x2^2) -(x1^2) + (y2^2) - (y1^2);
k4=(-2*x1)+(2*x3);
k5=(-2*y1)+(2*y3);
k6=(x3^2)-(x1^2)+(y3^2)-(y1^2);
%coordinates of guiding centre
b=((k1*k6)-(k3*k4))/((k1*k5)-(k2*k4));
a=(k3-(k2*b))/k1;
gcx = a;
Phoebe
on 28 Mar 2014
Phoebe
on 28 Mar 2014
Categories
Find more on Performance and Memory in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!