How do I implement surfc in app designer? - matlab

I have a problem, in matlab i can code to graph 3D plot of complex function with surfc this is my code for that :\
figure
X=-2*pi:0.2:2*pi;
Y=-2*pi:0.2:2*pi;
[x,y]=meshgrid(X,Y);
z=3*x+5i*y;
sc=surfc(x,y,abs(z))
xlabel('Re(x)');
ylabel('Im(y)');
colormap jet
colorbar
But here i want to implement this into app designer. I want user to input the complex function they have in cartesian with x and y (not polar), and then showing that plot to them. But when I run with the same code with a little bit of changes, I always get the error message : "Error using surfc. The surface z must contain more than one row or column.".
Here is my app designer callbacks :
% Button pushed function: MakeGraphButton
function MakeGraphButtonPushed(app, event)
x=-2*pi:0.2:2*pi;
y=-2*pi:0.2:2*pi;
[x,y]=meshgrid(x,y);
z=app.ComplexFunctionEditField.Value;
axes(app.UIAxes);
surfc(x,y,abs(z))
axis equal
grid on
end
end
I expect that it will show the graph on the app that i design, but it just showing that error message. How to make this works?

You're taking the .Value of an edit field, so most likely that's a char. You're then using it as if you've evaluated some function of x and y, but you haven't! You might need something like
% Setup...
x = -2*pi:0.2:2*pi;
y = -2*pi:0.2:2*pi;
[x,y] = meshgrid(x,y);
% Get char of the function from input e.g. user entered '3*x+5i*y'
str_z = app.ComplexFunctionEditField.Value;
% Convert this to a function handle. Careful here, you're converting
% arbitrary input into a function!
% Should have more sanity checking that this isn't something "dangerous"
func_z = str2func( ['#(x,y)', str_z] );
% Use the function to evaluate z
z = func_z( x, y );
Now you've gone from a char input, via a function, to actually generating values of z which can be used for plotting

Related

Plot gradient in matlab and nothing but blank appears

I'm trying to plot the gradient of the real part of a complex function, however what I get is a blank figure. I do not understand what I am doing wrong since the code works with other functions (such as the imaginary part)
% Set up
x = -3:0.2:3;
y1 = (-3:0.2:3);
y = (-3:0.2:3)*1i;
[X, Y]= meshgrid(x,y);
% Complex variable s
s = X + Y;
% Complex function f(z)
z = s + 1./s;
figure
subplot(1,2,1);
[Dx, Dy] = gradient(real(z),.2,.5);
quiver(x,y1,Dx,Dy)
title('u(x,y) gradient, vector field');
%%Imaginary part
subplot(1,2,2)
contour(x,y1,imag(z),linspace(-10,10,100)); title('Contour of Im(f)');
xlabel('x'); ylabel('y'); %clabel(C3);
title('Imaginary part');
Here below is the image I get
I tried to rescale and resize the picture, the domain etc... but couldn't get the gradient to display (the arrows). What am I doing wrong here?
EDIT:
I found out it displays blank perhaps because there are some Inf and -Inf values in the Dy and Dx variables, is there an option to ignore these values or set them to 0?
It looks to me like it works, but the line width of your arrows is too small for you to see.
You can increase it by assigning a handle to the quiver plot like so:
hQuiver = quiver(x,y1,Dx,Dy);
And then, after the plot is created, change any of its many properties like so:
set(hQuiver,'LineWidth',4)
or do it all in the call to quiver:
hQuiver = quiver(x,y1,Dx,Dy,'LineWidth',4);
In this case it gives the following:
EDIT:
To answer your secondary question, you can set elements that are equal to +Inf or -Inf to any value you want using isinf:
Dx(isinf(Dx)) = 0;
and
Dy(isinf(Dy)) = 0;
It is not blank. You've plotted the quiver diagram (usually used in optical flow diagrams). It is giving an inward pointing arrow at each of the locations formed by the grid with points in x and y1.

Take fitted data from fit object

I use the following example taken from the site that describes fit. Returns an
object. Is it possible to take the data that refer to the fitted surface?
load franke
sf = fit([x, y],z,'poly23')
plot(sf,[x,y],z)
Thanks!
Here is a way to do it; but there is probably a cleaner one:
After getting your sf object, you can access its methods like so:
MethodName(sf)
See here for the list of available methods
So let's say you wish to plot the surface using a handle for the plot:
hPlot = plot(sf)
Then you can fetch the XData, YData and ZData using the handles like so:
X = get(hPlot,'XData')
Y = get(hPlot,'YData')
Z = get(hPlot,'ZData')
Might be a it cumbersome but it works. Note that you can also fetch the coefficients of the fitted surface like so:
coeffvalues(sf)
and the formula used to generate it:
formula(sf)
Therefore you could generate X, Y data and create Z values using meshgrid for example and you could then modify the surface as you wish.
EDIT Here is how you could create your own surface using the coefficients and the formula. Here I create an anonymous function with two input arguments (x and y) and use it to generate z values to plot. From the data obtained using plot(sf) I used x = 1:0.01:0.01:1 and y = 500:500:3000 but you could obviously change them.
I entered the formula manually in the function handle but there has to be a better way; I'm a bit in a hurry so I did not looked further into that but you could extract every element of the formula and multiply it by the right coefficient to automatically generate the formula.
Here is the whole code:
clear
clc
close all
load franke
sf = fit([x, y],z,'poly23')
c = coeffvalues(sf)
F = formula(sf)
%// Generate x and y values.
[x,y] = meshgrid(500:100:3000,0.01:.01:1);
%// There should be a better approach than manually entering the data haha.
%// Maybe use eval or feval.
MyFun = #(x,y) (c(1) + c(2)*x + c(3)*y +c(4)*x.^2 + c(5)*x.*y + c(6)*y.^2 + c(7)*(x.^2).*y + c(8)*x.*y.^2 + c(9)*y.^3);
%// Generate z data to create a surface
z = (MyFun(x,y));
figure
subplot(1,2,1)
plot(sf)
title('Plot using sf','FontSize',18)
subplot(1,2,2)
surf(x,y,z)
title('Plot using MyFun','FontSize',18)
Output:
[I know this is many years later, but I thought I'd add this for future visitors looking for answers]
There is a much simpler way to do this - use feval, or the implicit shortcuts to it by calling the fittype object itself. It did take me a little digging to find this when I needed it, it isn't particularly obvious.
From the feval MATLAB documentation:
Standard feval syntax:
y = feval(cfun,x)
z = feval(sfun,[x,y])
z = feval(sfun,x,y)
y = feval(ffun,coeff1,coeff2,...,x)
z = feval(ffun,coeff1,coeff2,...,x,y)
You can use feval to evaluate fits, but the following simpler syntax is recommended to evaluate these objects, instead of calling feval directly. You can treat fit objects as functions and call feval indirectly using the following syntax:
y = cfun(x) % cfit objects;
z = sfun(x,y) % sfit objects
z = sfun([x, y]) % sfit objects
y = ffun(coef1,coef2,...,x) % curve fittype objects;
z = ffun(coef1,coef2,...,x,y) % surface fittype objects;

How to mark co-ordinates of points in Octave using "plot" command?

I am using the plot command in Octave to plot y versus x values. Is there a way such that the graph also shows the (x,y) value of every coordinate plotted on the graph itself?
I've tried using the help command but I couldn't find any such option.
Also, if it isn't possible, is there a way to do this using any other plotting function?
Have you tried displaying a text box at each coordinate?
Assuming x and y are co-ordinates already stored in MATLAB, you could do something like this:
plot(x, y, 'b.');
for i = 1 : numel(x) %// x and y are the same lengths
text(x(i), y(i), ['(' num2str(x(i)) ',' num2str(y(i)) ')']);
end
The above code will take each point in your graph and place a text box (with no borders) in the format of (x,y) where x and y are the coordinates for all of the points.
Note: You may have to play around with the position of the text boxes, because the above code will place each text box right on top of each pair of co-ordinates. You can play around by adding/subtracting appropriate constants in the first and second parameters of the text function. (i.e. text(x(i) + 1, y(i) - 1, .......); However, if you want something quick and for illustrative purposes, then the above code will be just fine.
Here's a method I've used to do something similar. Generating the strings for the labels is the most awkward part, really (I only had a single number per label, which is a lot simpler)
x = rand(1, 10);
y = rand(1, 10);
scatter(x, y);
% create a text object for each point
t = text(x, y, '');
% generate a cell array of labels - x and y must be row vectors in this case
c = strsplit(sprintf('%.2g,%.2g\n',[x;y]), '\n');
c(end) = []; % the final \n gives us an extra empty cell, remove it
c = c'; % transpose to match the dimensions of t
% assign each label to each text object
set(t, {'String'}, c);
You may want to play around with various properties like 'HorizontalAlignment', 'VerticalAlignment' and 'Margin' to tweak the label positions to your liking.
After a little more thought, here's an alternative, more robust way to generate a suitable cell array of coordinate labels:
c = num2cell([x(:) y(:)], 2);
c = cellfun(#(x) sprintf('%.2g,%.2g',x), c, 'UniformOutput', false);
There is a very useful package labelpoints
in MathWorks File Exchange that does exactly that.
It has a lot of convenient features.

4D plot display variables with data cursor Matlab

I am having trouble figuring out how display 4 variables in my plot.
I want to vary the independent variables X,V, to produce the dependent variables Y and Z.
Y is a function of X AND V. And Z is a function of Y AND X.
This may be easier to see the dependencies: X, V, Y(X,V), Z(X,Y(X,V)).
I have used the surf function to plot X,Y,Z, but I also want to know the values of V, which I cannot currently ascertain.
Here is some test data to illustrate:
X = linspace(1,5,5)
V = linspace(1,5,5)
Capture = []
for j = 1:length(V)
Y = X.*V(j)
Capture = [Capture;Y]
end
[X,V] = meshgrid(X,V);
Z = Capture.*X
surf(X,Y,Z)
If I use the data cursor, I can see values of X,Y,Z, but I would also like to know the values of V. I know that the way I have it set up is correct because if I make two plots, say:
surf(X,Y,Z)
surf(X,V,Z)
and then use the data cursor to go on the same point of X and Z for both graphs the values for V and Y are what they should be for that point (X,Z).
Is there anyway to show the values for X,Y,V and Z without having to generate two separate graphs?
Thanks!
Using color as your 4th dimension is a possibility (whether it looks good to you is a matter of taste).
surf(X,Y,Z,V); #% 4th arg (V) is mapped onto the current colormap
You can change the colormap to suit your tastes.
colorbar #% displays a colorbar legend showing the value-color mapping
Edit: The questioner wants to see exactly the data in the not-shown array, rather than just a color. This is a job for custom data cursor function. Below I've implemented this using purely anonymous functions; doing it within a function file would be slightly more straightforward.
#% Step 0: create a function to index into an array...
#% returned by 'get' all in one step
#% The find(ismember... bit is so it returns an empty matrix...
#% if the index is out of bounds (if/else statements don't work...
#% in anonymous functions)
getel = #(x,i) x(find(ismember(1:numel(x),i)));
#% Step 1: create a custom data cursor function that takes...
#% the additional matrix as a parameter
myfunc = #(obj,event_obj,data) {...
['X: ' num2str(getel(get(event_obj,'position'),1))],...
['Y: ' num2str(getel(get(event_obj,'position'),2))],...
['Z: ' num2str(getel(get(event_obj,'position'),3))],...
['V: ' num2str(getel(data,get(event_obj,'dataindex')))] };
#% Step 2: get a handle to the datacursormode object for the figure
dcm_obj = datacursormode(gcf);
#% Step 3: enable the object
set(dcm_obj,'enable','on')
#% Step 4: set the custom function as the updatefcn, and give it the extra...
#% data to be displayed
set(dcm_obj,'UpdateFcn',{myfunc,V})
Now the tooltip should display the extra data. Note that if you change the data in the plot, you'll need to repeat Step 4 to pass the new data into the function.

maybe matrix plot!

for an implicit equation(name it "y") of lambda and beta-bar which is plotted with "ezplot" command, i know it is possible that by a root finding algorithm like "bisection method", i can find solutions of beta-bar for each increment of lambda. but how to build such an algorithm to obtain the lines correctly.
(i think solutions of beta-bar should lie in an n*m matrix)
would you in general show the methods of plotting such problem? thanks.
one of my reasons is discontinuity of "ezplot" command for my equation.
ok here is my pic:
alt text http://www.mojoimage.com/free-image-hosting-view-05.php?id=5039TE-beta-bar-L-n2-.png
or
http://www.mojoimage.com/free-image-hosting-05/5039TE-beta-bar-L-n2-.pngFree Image Hosting
and my code (in short):
h=ezplot('f1',[0.8,1.8,0.7,1.0]);
and in another m.file
function y=f1(lambda,betab)
n1=1.5; n2=1; z0=120*pi;
d1=1; d2=1; a=1;
k0=2*pi/lambda;
u= sqrt(n1^2-betab^2);
wb= sqrt(n2^2-betab^2);
uu=k0*u*d1;
wwb=k0*wb*d2 ;
z1=z0/u; z1_b=z1/z0;
a0_b=tan(wwb)/u+tan(uu)/wb;
b0_b=(1/u^2-1/wb^2)*tan(uu)*tan(wwb);
c0_b=1/(u*wb)*(tan(uu)/u+tan(wwb)/wb);
uu0= k0*u*a; m=0;
y=(a0_b*z1_b^2+c0_b)+(a0_b*z1_b^2-c0_b)*...
cos(2*uu0+m*pi)+b0_b*z1_b*sin(2*uu0+m*pi);
end
fzero cant find roots; it says "Function value must be real and finite".
anyway, is it possible to eliminate discontinuity and only plot real zeros of y?
heretofore,for another function (namely fTE), which is :
function y=fTE(lambda,betab,s)
m=s;
n1=1.5; n2=1;
d1=1; d2=1; a=1;
z0=120*pi;
k0=2*pi/lambda;
u = sqrt(n1^2-betab^2);
w = sqrt(betab^2-n2^2);
U = k0*u*d1;
W = k0*w*d2 ;
z1 = z0/u; z1_b = z1/z0;
a0_b = tanh(W)/u-tan(U)/w;
b0_b = (1/u^2+1/w^2)*tan(U)*tanh(W);
c0_b = -(tan(U)/u+tanh(W)/w)/(u*w);
U0 = k0*u*a;
y = (a0_b*z1_b^2+c0_b)+(a0_b*z1_b^2-c0_b)*cos(2*U0+m*pi)...
+ b0_b*z1_b*sin(2*U0+m*pi);
end
i'd plotted real zeros of "y" by these codes:
s=0; % s=0 for even modes and s=1 for odd modes.
lmin=0.8; lmax=1.8;
bmin=1; bmax=1.5;
lam=linspace(lmin,lmax,1000);
for n=1:length(lam)
increment=0.001; tolerence=1e-14; xstart=bmax-increment;
x=xstart;
dx=increment;
m=0;
while x > bmin
while dx/x >= tolerence
if fTE(lam(n),x,s)*fTE(lam(n),x-dx,s)<0
dx=dx/2;
else
x=x-dx;
end
end
if abs(real(fTE(lam(n),x,s))) < 1e-6 %because of discontinuity some answers are not correct.%
m=m+1;
r(n,m)=x;
end
dx=increment;
x=0.99*x;
end
end
figure
hold on,plot(lam,r(:,1),'k'),plot(lam,r(:,2),'c'),plot(lam,r(:,3),'m'),
xlim([lmin,lmax]);ylim([1,1.5]),
xlabel('\lambda(\mum)'),ylabel('\beta-bar')
you see i use matrix to save data for this plot.
![alt text][2]
because here lines start from left(axis) to rigth. but if the first line(upper) starts someplace from up to rigth(for the first figure and f1 function), then i dont know how to use matrix. lets improve this method.
[2]: http://www.mojoimage.com/free-image-hosting-05/2812untitled.pngFree Image Hosting
Sometimes EZPLOT will display discontinuities because there really are discontinuities or some form of complicated behavior of the function occurring there. You can see this by generating your plot in an alternative way using the CONTOUR function.
You should first modify your f1 function by replacing the arithmetic operators (*, /, and ^) with their element-wise equivalents (.*, ./, and .^) so that f1 can accept matrix inputs for lambda and betab. Then, run the code below:
lambda = linspace(0.8,1.8,500); %# Create a vector of 500 lambda values
betab = linspace(0.7,1,500); %# Create a vector of 500 betab values
[L,B] = meshgrid(lambda,betab); %# Create 2-D grids of values
y = f1(L,B); %# Evaluate f1 at every point in the grid
[c,h] = contour(L,B,y,[0 0]); %# Plot contour lines for the value 0
set(h,'Color','b'); %# Change the lines to blue
xlabel('\lambda'); %# Add an x label
ylabel('$\overline{\beta}$','Interpreter','latex'); %# Add a y label
title('y = 0'); %# Add a title
And you should see the following plot:
Notice that there are now additional lines in the plot that did not appear when using EZPLOT, and these lines are very jagged. You can zoom in on the crossing at the top left and make a plot using SURF to get an idea of what's going on:
lambda = linspace(0.85,0.95,100); %# Some new lambda values
betab = linspace(0.95,1,100); %# Some new betab values
[L,B] = meshgrid(lambda,betab); %# Create 2-D grids of values
y = f1(L,B); %# Evaluate f1 at every point in the grid
surf(L,B,y); %# Make a 3-D surface plot of y
axis([0.85 0.95 0.95 1 -5000 5000]); %# Change the axes limits
xlabel('\lambda'); %# Add an x label
ylabel('$\overline{\beta}$','Interpreter','latex'); %# Add a y label
zlabel('y'); %# Add a z label
Notice that there is a lot of high-frequency periodic activity going on along those additional lines, which is why they look so jagged in the contour plot. This is also why a very general utility like EZPLOT was displaying a break in the lines there, since it really isn't designed to handle specific cases of complicated and poorly behaved functions.
EDIT: (response to comments)
These additional lines may not be true zero crossings, although it is difficult to tell from the SURF plot. There may be a discontinuity at those lines, where the function shoots off to -Inf on one side of the line and Inf on the other side of the line. When rendering the surface or computing the contour, these points on either side of the line may be mistakenly connected, giving the false appearance of a zero crossing along the line.
If you want to find a zero crossing given a value of lambda, you can try using the function FZERO along with an anonymous function to turn your function of two variables f1 into a function of one variable fcn:
lambda_zero = 1.5; %# The value of lambda at the zero crossing
fcn = #(x) f1(lambda_zero,x); %# A function of one variable (lambda is fixed)
betab_zero = fzero(fcn,0.94); %# Find the value of betab at the zero crossing,
%# using 0.94 as an initial guess