I have a problem about matlab code. I have a specific one variable function, and i want to assign a vector or array in this function as a x value. But i didn't reach success.
A part of my code is at below:
a=-5; b=10; n=20; %[a,b] interval range and n is number of interval
sz = (b-a)/n; %interval size
t=1; %iteration number
for i=1:n
I(i,:,t) = [a+(i-1)*sz a+i*sz]; %interval
x(i,:,t) = a+(i-0.5)*sz; %midpoint of interval
end
f= x.^2-3.*x+5; %my sample function
for i=1:n
if i==1
j=i+1;
neigbor(i,:,t) = I(j,:,t); %neigbor of interval I1's
h_f(i,:,t) =abs(f(x(i,:,t))-f(x(j,:,t))); %heuristic value
prob(i,:,t)=(ph(j,:,t).*h_f(i,:,t))./(ph(j,:,t).*h_f(i,:,t)); %probability
...
Other if conditions are following this code, but i check this below portion with sample i and j value, it gives error like this : "Subscript indices must either be real positive integers or logicals."
h_f(i,:,t) =abs(f(x(i,:,t))-f(x(j,:,t)));
What don't i know? What is my mistake? Can you suggest anything? If you need complete code, i can post.
Edit : Actually this function f returns value by using itself. But it doesn't return value in comment h_f(i,:,t)= abs((f(x(i,:,t)-x(j,:,t))
Solution Edit: After creating separate function m file, and calling in main function. Don't need to write x array in f.
In Matlab, you need to declare functions in a separate .m file. I created a separate file "f.m" and inserted the following code:
function return_val = f(x)
return_val = x.^2-3.*x+5; %my sample function
end
Then, in your main file, you can call this function as follows:
a=-5; b=10; n=20; %[a,b] interval range and n is number of interval
sz = (b-a)/n; %interval size
t=1; %iteration number
for i=1:n
I(i,:,t) = [a+(i-1)*sz a+i*sz]; %interval
x(i,:,t) = a+(i-0.5)*sz; %midpoint of interval
end
f = f(x)
Hope this helps.
As was posted you can create f as a function in a file but you can also inline the function with a handle. This is done as follows:
f = #(x) x.^2 - 3.*x + 5;
The f is the function handle with x as an input, see more information here: http://www.mathworks.com/help/matlab/matlab_prog/creating-a-function-handle.html.
This new f is then used as you would expect.
>> f(2)
ans =
3
>> f(5)
ans =
15
>> f(1:3)
ans =
3 3 5
>> f(4:10)
ans =
9 15 23 33 45 59 75
Related
I am attempting to write a recursive code that takes an input n and outputs the nth term of the Fibonacci sequence, without using any loops or any of MATLABS inbuilt functions.
for exemple:
fibo(6)
ans = 8
I am having trouble with writing the code recursively, and would really appreciate some help.
with a loop I wrote:
function f = fib1(n)
if n <= 1
f = 1;
else
f = fib1(n-1) + fib1(n-2);
end
end
If you want to get 8 for fib1(6), that means you need to start your fibonacci sequence from n=1. However, you code indicates that you start from n=0. In this case, you should use n <=2 in your if-else statement, i.e.,
function f = fib1(n)
if n <= 2
f = 1;
else
f = fib1(n-1) + fib1(n-2);
end
end
such that
>> fib1(6)
ans = 8
If you don't want to use any recursion, you can try the code below
function f = fib2(n)
f = (((1+sqrt(5))/2)^n - ((1-sqrt(5))/2)^n)/sqrt(5);
end
which gives
>> fib2(6)
ans = 8
Hi I am new to matlab so not familiar with its grammar.
I want to write a function to solve some functions using specific algo.
What I want to do is to write a function using another function which I want to slove as input.
For example, if I want to get the root of x^2 - 1 = 0 ,I need to plug in this function as in input.
my code is like
function [y] = brent(f, x0, x1, max_iter, tolerance)
fx0 = f(x0)
fx1 = f(x1)
......
end
f is the function I want to solve. My question is how should I write the code so the function 'brent' can use the function 'f' to calculate the values at specific points.
ex. In the second line, I need to get the value of f(x0) (x0 is a point).
Matlab talks about function handles. Those can be input parameter as anything:
Write your main function:
function a = func(f,x)
a = f(x) + 7;
Define your function to be input, and call 'normally'
>> myfun = #(x) x^2-1;
>> func(myfun,3)
ans =
15
>> func(#sin,0)
ans =
7
see:
https://se.mathworks.com/help/matlab/matlab_prog/creating-a-function-handle.html
When defining a function, say TEST = #(t) t.^2. If the input is a vector, say [1,2,3,4], TEST([1,2,3,4]) = [1,4,9,16].
Can we do similar thing if the function defined is in script form? What I mean is that if I have a script, say TEST.m such that ret = TEST(x,y,z) which outputs a value when knowing numerical values of x, y and z. Suppose I want to calculate 100 different values of z ranging from 1 to 100 when x, y are fixed, say at 0, 1 respectively. Is it possible to output TEST(0,1,1:1:100) without writing a for loop or changing any contents of the script TEST.m?
The reason to ask such question comes from the computation time. Usually, the script I have may be a little complicated so that the calculate of a single value may take few minutes to go. Writing for-loop to output it can be very time-consuming. I think of writing parfor loop, but the computation time is still long to me for further uses. I wonder if I can calculate all the 100 values at a time. I am a starter of programmer, and I hope I can get satisfactory answers after this post. Thanks for all your help.
You cab define a new anonymous function to get the fixed values as parameters, and the vector as input. Then use arrayfun to compute it on all values of the array.
Say you have this functions:
function ret = TEST(x,y,z)
ret = f(x)+g(y)+h(z);
end
function r = f(x)
r = x^2;
end
function r = g(y)
r = y^3;
end
function r = h(z)
r = z^4;
end
And you call it from:
x = 2;
y = 3;
z = 1:5;
T = #(z) TEST(x,y,z);
arrayfun(T,z)
So T is a new function that treat x and y as constants, and only have z as input. Then arrayfun takes T and compute it for every element in z, and you get:
ans =
32 47 112 287 656
Now, you can use arrayfun with more vectors, like [a,b,c] = arrayfun(T,z,w,v), if x and y can stay constant.
Hopes it answers your question ;)
I have the following anonymous function:
f = #(x)x^2+2*x+1
I'm using this so that I use it in the following way:
f(0) = 1
But what if I want to find the derivative of such a function while still keeping it's anonymous function capability? I've tried doing the following but it doesn't work:
f1 = #(x)diff(f(x))
but this just returns
[]
Any thoughts on how to accomplish this?
Of course I could manually do this in 3 seconds but that's not the point...
If you have symbolic math toolbox, you can use symbolic functions to achieve the desired as follows:
syms x
myFun=x^2+2*x+1;
f=symfun(myFun,x);
f1=symfun(diff(f),x);
%Check the values
f(2)
f1(2)
You should get 9 and 6 as answers.
When you do diff of a vector of n elements it just outputs another vector of n-1 elements with the consecutive differences.. so when you put a 1 element vector you get an empty one.
A way to go would be to decide an epsilon and use the Newton's difference quotient:
epsilon = 1e-10;
f = #(x) x^2+2*x+1;
f1 = #(x) (f(x+epsilon) - f(x)) / epsilon;
or just do the math and write down the formula:
f1 = #(x) 2*x+2;
http://en.wikipedia.org/wiki/Numerical_differentiation
#jollypianoman this works to me. Actually you need to say that the symfun has to be evaluate using eval command, then you get all the features of an anonymous function. the best is to read the example below...
clear
N0=1;N1=5;
N=#(t) N0+N1*sin(t);
syms t
Ndot=symfun(diff(N(t)),t);
Ndot_t=#(t) eval(Ndot);
Ndot_t(0)
ans = 5
Ndot_t(1)
ans = 2.7015
[tstop] = fsolve(Ndot_t,pi/3)
tstop =
1.5708
cheers,
AP
How do I plot the value of Approximation - Answer as s varies in the code below? If you look at my code below, you can see the method I used (I put it in a separate file).
However, it does not show me a graph from 1 to 1000. Instead the graph is from 999 to 1001 and does not have any points on it.
for s = 1:1000
error = LaplaceTransform(s,5) - (antiderivative(1,s)-antiderivative(0,s));
end
plot(s,error);
title('Accuracy of Approximation');
xlabel('s');
ylabel('Approximation - Exact Answer');
The functions used:
function g = LaplaceTransform(s,N);
% define function parameters
a=0;
b=1;
h=(b-a)/N;
x = 0:h:1;
% define function
g = ff(x).*exp(-s*x);
% compute the exact answer of the integral
exact_answer=antiderivative(b,s)-antiderivative(a,s)
% compute the composite trapezoid sum
If=0;
for i=1:(N-1)
If=If+g(i).*h;
end;
If=If+g(1).*h/2+g(N).*h/2;
If
with
function fx=ff(x)
fx=x;
and
function fx=antiderivative(x,s);
fx= (-exp(-s*x)*(s*x+1))/(s^2);
Any help would be appreciated. Thanks.
The following
for s = 1:1000
error = LaplaceTransform(s,5) - (antiderivative(1,s)-antiderivative(0,s));
end
plot(s,error);
already has several issues. The two main ones are that error is getting overwritten at each iteration, as #Amro has pointed out, and that s, your loop variable, is a scalar.
Thus, you need to write
difference = zeros(1000,1); %# preassignment is good for you
for s = 1:1000
difference(s) = LaplaceTransform(s,5) - (antiderivative(1,s)-antiderivative(0,s));
end
plot(1:1000,difference);
There is another error in the LaplaceTransform function
function g = LaplaceTransform(s,N);
[...]
g = ff(x).*exp(-s*x); %# g is an array
[...]
If %# If is calculated, but not returned.
I assume you want to write
function If = LaplaceTransform(s,N);
instead, because otherwise, you try to assign the array g to the scalar difference(s).