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 ax 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 "fm" 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.