More efficient alternatives to eval function in matlab (or how to print in 3d without previous evaluation)

StackOverflow https://stackoverflow.com/questions/20890526

Domanda

I want to print this function:

f=cos(q1+q2)

I set the range of both q1 and q2 like this:

q1=-pi:0.01:pi
q1=-pi:0.01:pi

then, to use mesh (it's not that I like this function,is the only one I found) I have to:

1)create a meshgrid for x and y 2)create a matrix for my f containing its values for the meshgrid so

[X,Y]=meshgrid(x,y)

now,for the 2) if I do

for i=1:length(x), 
 for j=1:length(y), 
  Z(i,j)=cos(x(i)+y(j)); 
 end;
end;

and then mesh(X,Y,Z) it works well

BUT

if I do

for i=1:length(x), 
 for j=1:length(y), 
  Z(i,j)=eval(subs(f,[q1,q2],[x(i),y(j)])); 
 end;
end;

it takes half an hour (literally) to get Z,and I get it in a horrible way (I have elements like cos(1194939423423424/4214242444122)

I've seen someone using a form like this k=@a,b f but I can't find it on the documentation and I supose is the same thing of the subs command. Why the second case is that slower? I want to create a function that does it taking f as input,but if I have to hardcode it in the for I can't.

I'm totally fine if you can tip me a way to print in 3d AND get the level curves without using those matrix,but if you can answer my question I'd prefer it

È stato utile?

Soluzione

The reason it takes forever to calculate Z is that you don't preallocate the array.

If f can be vectorized, you can create your plot very easily:

[X,Y] = meshgrid(-pi:0.01:pi,-pi:0.01:pi);
f = @(x,y)cos(x+y);
Z = f(X,Y); %# or call directly Z=cos(X+Y)

mesh(X,Y,Z)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top