Im trying to plot a 3D function with Matlab, my script contains the following :
function f=Untitled(s1 ,s2 , s3)
s =[s1 s2 s3];
f= 0.0663 + 0.2099245 *(s(1)^2+s(2)^2+s(3)^2);
endfunction
xdata = linspace(36,36,36);
ydata = linspace(36,36,36);
zdata = linspace(36,36,36);
contour( xdata , ydata , zdata , [1 36 72 110])
I got the following error:
Error in ====> Untitled at 2
s=[s1 s2 s3]
I'm newest in Matlab, can any one help me to resolve this issue?
There are many issues in your code:
s = [s1 s2 s3];
This concatenates s1 s2 and s3 horizontally to variable s
To do that, "the number of rows in each variable should be same". That is the cause of your error.
You need to check the dimensions of the variable you passed to the
function untitled
endfunction is Octave syntax. You just need to use end for
Matlab
Then you are using s(1), s(2), s(3) separately inside your
function.
Then why did you cat them? you could have used the corresponding
variables itself like this:
f= 0.0663 + 0.2099245 *(s1^2+s2^2+s3^2);
Then you are using linspace(I don't know what you actually intend to do with linspace) for replicating values. Although this
doesn't pose any issues, there is a separate built-in function for
that called
repmat
You could use it like this: repmat(36,[1,36])
Note: Also name your function to any other name for good practice
Related
I want to use symbolic symbol to solve a system of linear equation. So I prepare the following code.
A=[1,2;3,4];
% syms x
x=sym('x_%d',[2 1]);
eqn=A*x==[1;2];
result=solve(eqn,x)
Interestingly, it works, but when I read the variable result, it gives a 1X1 struct with x_1 and x_2 are 1X1 sym. But what I expect get should be 2 real values, why? Could someone explain it? Remark: do not want to use A^-1*[1;2] to obtain the answer.
If you set the output to single variable solve returns a structure
data type that contains all the solutions, to get each solution use
the dot. assignment, like result.x_1 or result.x_2
The code is as follows
A=[1,2;3,4];
% syms x
x=sym('x_%d',[2 1]);
eqn=A*x==[1;2];
result = solve(eqn,x);
result.x_1
% 0
result.x_2
% 1/2
If you want to have result as an array, use multiple output format, like
result(1) for the first variable, result(2) for the second variable
The code is as follows
A=[1,2;3,4];
% syms x
x=sym('x_%d',[2 1]);
eqn=A*x==[1;2];
[result(1), result(2)] = solve(eqn,x);
result
% result = [0 , 1/2]
I would like to create a MATLAB function with vector inputs. The problem is that the inputs of a function created by matlabFunction() has only scalar inputs.
x = sym('x',[2 1]);
y = sym('y',[2 1]);
f=x(1)+x(2)+y(1)+y(2);
matlabFunction(f,'file','testFunction.m');
matlabFunction(f,'file','testFunction.m','vars',[x,y]); % tried with different options but doesn't work
This is the result (with x1,x2,y1,y2 inputs instead of x,y):
function f = testFunction(x1,x2,y1,y2)
%TESTFUNCTION
% F = TESTFUNCTION(X1,X2,Y1,Y2)
% This function was generated by the Symbolic Math Toolbox version 8.2.
% 10-Apr-2019 21:28:40
f = x1+x2+y1+y2;
Is there a solution to this problem within MATLAB? Or do I need to write a program opening the file as txt and replacing the words...
Update: I managed to solve the problem. For me, the best solution is the odeToVectorField() function.
Manually it is more difficult to give vector inputs to a function created by matlabFunction(). One way is the following:
syms y;
f=str2sym('y(1)+y(2)');
matlabFunction(f,'File','fFunction','Vars',y);
With this method, you need to manipulate the equation as a string (which is possible but not practical...), then re-convert it to symbolic expression.
If you check the result of f=x(1)+x(2)+y(1)+y(2) you will see that it is also scalar. Do simple test:
x = sym('x',[2 1]);
y = sym('y',[2 1]);
f=x(1)+x(2)+y(1)+y(2);
disp(f)
The results is x1 + x2 + y1 + y2. So there's nothing wrong with your matlabFunction expression, it just save what you give. If you need it to be stored in the form x(1)+x(2)+y(1)+y(2) you need to rewrite your f expression so it will be stored in vector form, until passing it to matlabFunction. Or alternatively you can create your file structure manualy using fprintf, look docs.
I'm working on chapter 8 of A Course in Mathematical Biology. The textbook uses Maple, but includes this link, Computer course of Chapter 8 in Matlab. I'm told to put the following in an m-file:
% defining a recursive function in an m-file
function y = plot_traj(a)
RM = inline('a*x.*exp(-x)', 'a', 'x')
% Note that we are using an inline function. Sometimes it’s easier to do this.
% collecting list of x-coordinates
for i = 1:31,
X(i) = i - 1
end
% collecting list of y-coordinates
for i = 1:30,
Y(i+1)=RM(a,iter(i));
iter(i+1) = Y(i+1);
end
y = plot(X, Y, '*');
Now, save your m-file (as plot traj.m) and close it. Type the following into the command window:
>> plot traj(0.8)
>> plot traj(1.0)
>> plot traj(5.0)
>> plot traj(8.0)
>> plot traj(13.0)
>> plot traj(14.5)
>> plot traj(20.0)
However, when I type plot traj(0.8) into the command window I get this:
>> plot_traj(0.8)
Undefined function or variable "iter".
Error in plot_traj (line 13)
Y(i)=RM(a,iter(i));
I don't see anything wrong with line 13, and I've made sure that my code is exactly what is in the chapter. I've been doing fine with the codes up until this point. I'd appreciate it if anyone could provide some assistance. Thank you.
The problem at line 13 is that the iter local variable array has not been defined. So on the first iteration, the code tries to access iter(1) and fails. I looked at the link you provided and they missed it too. Based on previous examples in the Matlab_Course.pdf (and figure 8.6), the iter array should be initialized as
iter(1) = 1.0;
Just add this line prior to the for loop and you should be good to continue. I suspect also that this line should be added too (again based on the document)
Y(1)=iter(1);
to make sure that both iter and Y have the same length.
Note that it is a good habit to pre-allocate memory to arrays to avoid the internal resizing of matrices/arrays on each iteration of the loop (which can have a negative impact on performance). For this loop
for i = 1:30,
Y(i+1)=RM(a,iter(i));
iter(i+1) = Y(i+1);
end
you can observe that i iterates over 1 through 30, and we always populate Y(i+1) and iter(i+1). So both Y and iter are 31x1 vectors. We can allocate memory to each prior to entering the for loop as
iter = zeros(31,1);
Y = zeros(31,1);
iter(1) = 1;
Y(1) = iter(1);
The same should be done for X as well.
I want to use fit in MATLAB for two dimensions.
I defined function separately and then called it with fittype
x has two columns!
f=fittype('#(x)myfun(beta1, beta2,beta3, x)')
and then customize in options my start point and algorithm.
then use [results, goodness]=fit(x, zdata,f, options), but I have a error
??? Too many inputs to FITTYPE function.
Error in ==> fit at 443
errstr = handleerr( errid, errmsg, suppresserr );
I also tried with [results, goodness]=fit([x(:,1), x(:,2)], zdata,f, options),
and still have the same problem.
I used fit -all
XDATA must be a matrix with one to two columns.
Error in ==> fit at 115
errstr = handleerr('curvefit:fit:xDataMustBeColumnVector', ...
for me sounds meaningles , since I have my x in two columns!!!!
and then which fit -all
/Applications/matlab/MATLAB_R2010a.app/toolbox/curvefit/curvefit/fit.m
/Applications/matlab/MATLAB_R2010a.app/toolbox/stats/#ProbDistUnivParam/fit.m % ProbDistUnivParam method
/Applications/matlab/MATLAB_R2010a.app/toolbox/stats/#NaiveBayes/fit.m % NaiveBayes method
/Applications/matlab/MATLAB_R2010a.app/toolbox/stats/#gmdistribution/fit.m % gmdistribution method
could you please help me to use fit and fittype to fit my 2 dimension data?
{please don't introduce me meshgrid and other commands.}
You need to add the parameter 'numindep' = 2 which indicates that your fit is for a surface (i.e has two independent variables).
Here's an example using your function with the Franke data using a string:
load franke
ft = fittype('myfun(beta1, beta2, beta3, [x, y])', 'numindep', 2)
[results, goodness] = fit([x, y], z, ft)
Here's an example using your function with the Franke data using an anonymous function:
load franke
ft = fittype(#(beta1,beta2,beta3, x, y)myfun(beta1, beta2,beta3, [x, y]), 'numindep', 2)
[results, goodness] = fit([x, y], z, ft)
I have one file with the following code:
function fx=ff(x)
fx=x;
I have another file with the following code:
function g = LaplaceTransform(s,N)
g = ff(x)*exp(-s*x);
a=0;
b=1;
If=0;
h=(b-a)/N;
If=If+g(a)*h/2+g(b)*h/2;
for i=1:(N-1)
If=If+g(a+h*i)*h;
end;
If
Whenever I run the second file, I get the following error:
Undefined function or variable 'x'.
What I am trying to do is integrate the function g between 0 and 1 using trapezoidal approximations. However, I am unsure how to deal with x and that is clearly causing problems as can be seen with the error.
Any help would be great. Thanks.
Looks like what you're trying to do is create a function in the variable g. That is, you want the first line to mean,
"Let g(x) be a function that is calculated like this: ff(x)*exp(-s*x)",
rather than
"calculate the value of ff(x)*exp(-s*x) and put the result in g".
Solution
You can create a subfunction for this
function result = g(x)
result = ff(x) * exp(-s * x);
end
Or you can create an anonymous function
g = #(x) ff(x) * exp(-s * x);
Then you can use g(a), g(b), etc to calculate what you want.
You can also use the TRAPZ function to perform trapezoidal numerical integration. Here is an example:
%# parameters
a = 0; b = 1;
N = 100; s = 1;
f = #(x) x;
%# integration
X = linspace(a,b,N);
Y = f(X).*exp(-s*X);
If = trapz(X,Y) %# value returned: 0.26423
%# plot
area(X,Y, 'FaceColor',[.5 .8 .9], 'EdgeColor','b', 'LineWidth',2)
grid on, set(gca, 'Layer','top', 'XLim',[a-0.5 b+0.5])
title('$\int_0^1 f(x) e^{-sx} \,dx$', 'Interpreter','latex', 'FontSize',14)
The error message here is about as self-explanatory as it gets. You aren't defining a variable called x, so when you reference it on the first line of your function, MATLAB doesn't know what to use. You need to either define it in the function before referencing it, pass it into the function, or define it somewhere further up the stack so that it will be accessible when you call LaplaceTransform.
Since you're trying to numerically integrate with respect to x, I'm guessing you want x to take on values evenly spaced on your domain [0,1]. You could accomplish this using e.g.
x = linspace(a,b,N);
EDIT: There are a couple of other problems here: first, when you define g, you need to use .* instead of * to multiply the elements in the arrays (by default MATLAB interprets multiplication as matrix multiplication). Second, your calls g(a) and g(b) are treating g as a function instead of as an array of function values. This is something that takes some getting used to in MATLAB; instead of g(a), you really want the first element of the vector g, which is given by g(1). Similarly, instead of g(b), you want the last element of g, which is given by g(length(g)) or g(end). If this doesn't make sense, I'd suggest looking at a basic MATLAB tutorial to get a handle on how vectors and functions are used.