0
$\begingroup$

Could you tell me please how to obtain separate values of "pi" depending on the value of N (code below)? For example If I write "pi1" I will get a value of "pi" for N(1) where N(1)=100. If I write "pi2" I will get "pi" for N(2)=1000 etc. I need it to compare the calculation time and the accuracy.

My CODE is:

R=1; 
N=[100,1000,10000,100000]; 

for k=1:1:4 
  toc
   x = 2*rand(N(k), 1)-1; 
   y = 2*rand(N(k), 1)-1; 
   in_circle = find((x.^2+y.^2)<R.^2); 
   N2 = size(in_circle, 1); 

   pi=4*N2/(N(k)*R.^2) 
  t=toc
end 

Actual OUTPUT is:

pi = 
3.120000000000000 
t = 
1.088773407512715e-004 

pi = 
3.208000000000000 
t = 
5.176135871781760e-005 

pi = 
3.145600000000000 
t = 
6.113194952018113e-005 

pi = 
3.143360000000000 
t = 
1.124470896283624e-004 

OUTPUT I would like to get:

pi1 = 
3.120000000000000 
t1 = 
1.088773407512715e-004 

pi2 = 
3.208000000000000 
t2 = 
5.176135871781760e-005 

pi3 = 
3.145600000000000 
t3 = 
6.113194952018113e-005 

pi4 = 
3.143360000000000 
t4 = 
1.124470896283624e-004 
$\endgroup$
4
$\begingroup$

If you really want the variables to be called pi1, pi2, ..., you can build the variable names using eval:

for k=1:1:4
  ...
  eval(['pi' num2str(k) ' = 4*N2/(N(k)*R.^2)'])
  ...
end

But a more typical thing to do would be to use an array:

for k=1:1:4
  ...
  pi(k) = 4*N2/(N(k)*R.^2)
  ...
end

If you're not planning on using the names of the pi variables later in your code, you might just use disp to write the statement that you actually want:

for k=1:1:4
  ...
  pi = 4*N2/(N(k)*R.^2)
  disp([num2str(k) ': ' num2str(4*N2/(N(k)*R.^2))])
  ...
end

Etc.

$\endgroup$
  • $\begingroup$ Alternatives to the eval Function from The MathWorks. Better than straight eval is genvarname, which is subject for future replacement by options only available in R2014a+. $\endgroup$ – horchler May 20 '14 at 22:48
  • $\begingroup$ That's not an alternative to eval. You might need getvarname to construct the variable name in a way that's legal, but you still have to do the eval. The example is right there in the page you linked to. $\endgroup$ – Bill Barth May 21 '14 at 1:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.