0

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
user1834153
  • 330
  • 5
  • 20
  • You don't need symbolic, nor `eval()`. However, I suspect you haven't phrased the question appropriately. The following produces a surf: `[q1,q2] = deal(-pi:0.1:pi); [q1,q2] = meshgrid(q1,q2) surf(q1,q2,q1+q2)` – Oleg Jan 02 '14 at 20:18

1 Answers1

0

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)
Jonas
  • 74,690
  • 10
  • 137
  • 177
  • could you tell me what exactly @(x,y)cos(x+y); means? – user1834153 Jan 02 '14 at 22:47
  • @user3149593: `@(x,y)` is an anonymous (or lambda) function with two input arguments, that will internally be called `x` and `y`. `cos(x+y)` is what will be executed when the anonymous function is called. – Jonas Jan 03 '14 at 08:30
  • oh I see,it's like makinga .m file with as input args x and y and out=cos(x+y). ty very much – user1834153 Jan 03 '14 at 17:01