Reputation: 138
I'd like to make a function, that will be making a mesh plot. start x,y; dx,dy and end x,y will be inputted into a function. Z should be calculated like there:
if x>y
z =x^2-sin(x);
elseif x==y
z = 3;
else
z = 2*x+2*x;
end
I've made this code:
function []= mes(xp,xk,dx,yp,yk,dy)
x=[xp:dx:xk];
y=[yp:dy:yk];
zv=[];
for i=1:numel(x)
if x>y
z=x(i)^2-sin(y(i));
elseif x(i)==y(i)
z=3;
else
z=2*x(i)+2*y(i);
end
zv=[zv z];
end
[X,Y]=meshgrid(x,y);
figure
x
y
zv
mesh(X,Y,zv)
and got these error codes:
Error using mesh (line 70)
Z must be a matrix, not a scalar or vector.
Error in mes (line 21)
mesh(X,Y,zv)
Equation for z seems to work. I know, that there are many answers to simillar problems as mine, but when I make a simple equation for z it works, but not with this one.
Upvotes: 0
Views: 147
Reputation: 35525
Use Vectorization!
x=[xp:dx:xk];
y=[yp:dy:yk];
[X,Y]=meshgrid(x,y);
z=zeros(size(X));
z=2*X+2*Y;
z(X>Y)=X((X>Y)).^2-sin(Y((X>Y)));
z(X==Y)=3; % Careful with floating points!! maybe abs(X-Y)<0.00001 ?
mesh(X,Y,Z);
Upvotes: 1