How do I set a function to a variable in MATLAB - function

As a homework assignment, I'm writing a code that uses the bisection method to calculate the root of a function with one variable within a range. I created a user function that does the calculations, but one of the inputs of the function is supposed to be "fun" which is supposed to be set equal to the function.
Here is my code, before I go on:
function [ Ts ] = BisectionRoot( fun,a,b,TolMax )
%This function finds the value of Ts by finding the root of a given function within a given range to a given
%tolerance, using the Bisection Method.
Fa = fun(a);
Fb = fun(b);
if Fa * Fb > 0
disp('Error: The function has no roots in between the given bounds')
else
xNS = (a + b)/2;
toli = abs((b-a)/2);
FxNS = fun(xns);
if FxNS == 0
Ts = xNS;
break
end
if toli , TolMax
Ts = xNS;
break
end
if fun(a) * FxNS < 0
b = xNS;
else
a = xNS;
end
end
Ts
end
The input arguments are defined by our teacher, so I can't mess with them. We're supposed to set those variables in the command window before running the function. That way, we can use the program later on for other things. (Even though I think fzero() can be used to do this)
My problem is that I'm not sure how to set fun to something, and then use that in a way that I can do fun(a) or fun(b). In our book they do something they call defining f(x) as an anonymous function. They do this for an example problem:
F = # (x) 8-4.5*(x-sin(x))
But when I try doing that, I get the error, Error: Unexpected MATLAB operator.
If you guys want to try running the program to test your solutions before posting (hopefully my program works!) you can use these variables from an example in the book:
fun = 8 - 4.5*(x - sin(x))
a = 2
b = 3
TolMax = .001
The answer the get in the book for using those is 2.430664.
I'm sure the answer to this is incredibly easy and straightforward, but for some reason, I can't find a way to do it! Thank you for your help.

To get you going, it looks like your example is missing some syntax. Instead of either of these (from your question):
fun = 8 - 4.5*(x - sin(x)) % Missing function handle declaration symbol "#"
F = # (x) 8-4.5*(x-sin9(x)) %Unless you have defined it, there is no function "sin9"
Use
fun = #(x) 8 - 4.5*(x - sin(x))
Then you would call your function like this:
fun = #(x) 8 - 4.5*(x - sin(x));
a = 2;
b = 3;
TolMax = .001;
root = BisectionRoot( fun,a,b,TolMax );
To debug (which you will need to do), use the debugger.
The command dbstop if error stops execution and opens the file at the point of the problem, letting you examine the variable values and function stack.
Clicking on the "-" marks in the editor creates a break point, forcing the function to pause execution at that point, again so that you can examine the contents. Note that you can step through the code line by line using the debug buttons at the top of the editor.
dbquit quits debug mode
dbclear all clears all break points

Related

Cannot pass function handle as an argument of a function

I'm new to Matlab and I'm trying to write custom function in matlab that would take function handle as one of its arguments.
I'm getting this error all the time:
Error using subsindex
Function 'subsindex' is not defined for values of class 'function_handle'.
Trying to debug I performed following test: I run command x = fminbnd(#humps, 0.3, 1). I proceeded as expected - I got result x = 0.6370.
So I created custom function called train and I copied ALL the code of function fminbnd to the file train.m. The only thing that I changed is the name, so that code of functions fminbnd and train is now identical except for the names.
Now I run both functions with the same argument and the custom function throws error while original fminbnd returns correct answer.
Here is the code:
>> x = fminbnd(#humps, 0.3, 1)
x =
0.6370
>> x = train(#humps, 0.3, 1)
Error using subsindex
Function 'subsindex' is not defined for values of class 'function_handle'.
Here is header of function train (everything else is copied from fminbnd):
function [xf,fval,exitflag,output] = train(funfcn,ax,bx,options,varargin)
Where is the problem?
Doing a which train showed me that there is a function in the neural network toolbox of the same name.
/Applications/MATLAB_R2009b.app/toolbox/nnet/nnet/#network/train.m % network method
You may be running the nnet train.m rather than the one you think you're running. Are you in the directory containing your train.m? When I made sure I was in the right directory, I got it to work:
>> which train
/Users/myuserid/train.m
>> x = train(#humps,0.3,1)
x =
0.6370
Maybe you can name your file something else like myfminbnd.m instead?
Instead of duplicating the whole fminbnd function, try:
function varargout = myfminbnd(varargin)
varargout = cell(1,nargout(#fminbnd));
[varargout{:}] = fminbnd(varargin{:});
end
this will work as an "alias" to the existing function:
>> fminbnd(#(x)x.^3-2*x-5, 0, 2)
ans =
0.8165
>> myfminbnd(#(x)x.^3-2*x-5, 0, 2)
ans =
0.8165
(you can get the other output arguments as well)

Function callback ('StopFcn' , 'TimerFcn' )for audiorecorder object in MATLAB? [duplicate]

This question already exists:
Closed 10 years ago.
Possible Duplicate:
How can I use function callback ('StopFcn' , 'TimerFcn' )for audiorecorder object in MATLAB?
So I try to this code.
% assume fs,winsize,winshift is given.
T = 0.1; % in seconds
samples = cell{100,1};
r = audiorecorder(fs,16,1);
k=1;
r.TimerPeriod = 0.1;
r.StopFcn = 'samples{k} = getaudiodata(r);';
r.TimerFcn = {#get_pitch,samples{k},winsize,winshift};
while 1
record(r,T);
k=k+1;
end
I want to execute the function 'get_pitch(samples,fs,winsize,winshift)' while during recording through audiorecorder object.
But following exception occurs during execution.
1) after record(r,T) is executed. (StopFcn is now called) ??? Error using ==> eval Undefined function or variable 'r'.
2) after StopFcn is called (TimerFcn is now called) In this phase, get_pitch function have totally wrong parameters. For example, parameter in the position samples{k} change to 'audiorecorder object'.
It seems that I do not know exact use of 'StopFcn' & 'TimerFcn'.
Is there anyone who can give me some advice? I really appreciate all of your comments.
Looking at the example in the documentation I would recommend trying to call getaudiodata(r) in your loop rather than with the CallBack. So something like this:
% assume fs,winsize,winshift is given.
T = 0.1; % in seconds
samples = cell{100,1};
r = audiorecorder(fs,16,1);
k=1;
r.TimerPeriod = 0.1;
r.StopFcn = 'disp(''Completed sample '', k)';
r.TimerFcn = {#get_pitch,samples{k - 1},winsize,winshift};
while 1
record(r,T);
samples{k} = getaudiodata(r);
k=k+1;
end
Note I changed the r.TimerFcn to use samples{k - 1} instead of k because k will increment before the timerfcn gets called. So this might give you issues with your first sample, you'll have to tweak it a little. Also this is an infinite loop, which I'm sure you'll want to address.

Calling function with changing input parameters in a loop Matlab

I have caught myself in a issue, I know its not that difficult but I couldnt figure out how to implement it. I have an m file that looks like
clear;
PVinv.m_SwF=20e3
for m=1:1:70;
PVinv.m_SwF=PVinv.m_SwF+1e3;
Lmin = PVinv.InductanceDimens();
Wa_Ac = PVinv.CoreSizeModel();
PVinv.CoreSelect(Wa_Ac);
[loss_ind_core,loss_ind_copper] = PVinv.InductorLossModel(PVinv.m_L_Selected);
Total_Inductor_Loss=loss_ind_core+loss_ind_copper
plot(PVinv.m_SwF,Total_Inductor_Loss,'--gs');
hold on
xlim([10e3 90e3])
set(gca,'XTickLabel',{'10';'20';'30';'40';'50';'60';'70';'80';'90'})
grid on
xlabel('Switching Frequency [kHz]');
ylabel('Power loss [W]');
end
And the function that is of interest is CoreSelect(Wa_Ac)
function obj = CoreSelect(obj, WaAc)
obj.m_Core_Available= obj.m_Core_List(i);
obj.m_L_Selected.m_Core = obj.m_Core_Available;
end
I want to change the value of i from obj.m_Core_List(1) to obj.m_Core_List(27) within that for loop of main m file. How can I get the value of the function coreselect when I call it in main m file
For eg for m=1 to 70 I want the function to take the value of i=1 then execute till plot command and then same with but i=2 and so on
Any suggestion would be really helpful
I'm not sure I understand your question perfectly, but I think you want to pass an index i to the CoreSelect function, and loop i from 1 to 27 outside of the function. Try this:
function obj = CoreSelect(obj, WaAc, i)
...
end
for i=1:27,
PVInv.CoreSelect(WaAc,i);
end

Lua - How do I use a function from another script?

I've been looking around and I have not been able to find anything that has worked for me. I'm starting to learn more Lua and to start off I'm making a simple calculator. I was able to get each individual operation onto separate programs, but when I try to combine them I just can't get it to work. My script as it is now is
require "io"
require "operations.lua"
do
print ("Please enter the first number in your problem.")
x = io.read()
print ("Please enter the second number in your problem.")
y = io.read()
print ("Please choose the operation you wish to perform.")
print ("Use 1 for addition, 2 for subtraction, 3 for multiplication, and 4 for division.")
op = io.read()
op = 1 then
function addition
op = 2 then
function subtraction
op = 3 then
function multiplication
op = 4 then
function division
print (answer)
io.read()
end
and my operations.lua script is
function addition
return answer = x+y
end
function subtraction
return answer = x-y
end
function multiplication
return answer = x*y
end
function division
return answer = x/y
end
I've tried using
if op = 1 then
answer = x+y
print(answer)
if op = 2 then
answer = x-y
print(answer)
and I did that completing each operation. But it doesn't work. I can't even get the error code that it's returning because it closes so fast. What should I do?
In your example, make these changes: You require operations.lua without the extension. Include parameters in your operations function definitions. Return the operation expression directly versus returning a statement like answer = x+y.
All together:
Code for operations.lua
function addition(x,y)
return x + y
end
--more functions go here...
function division(x,y)
return x / y
end
Code for your hosting Lua script:
require "operations"
result = addition(5,7)
print(result)
result = division(9,3)
print(result)
Once you get that working, try re-adding your io logic.
Keep in mind that as it's coded, your functions will be defined globally. To avoid polluting the global table, consider defining operations.lua as a module. Take a look at the lua-users.org Modules Tutorial.
The right if-then-else syntax:
if op==1 then
answer = a+b
elseif op==2 then
answer = a*b
end
print(answer)
After: please check the correct function-declaration syntax.
After: return answer=x+y is incorrect. If you want set answer's value, set without return. If you want return the sum, please use return x+y.
And I think you should check Programming in Lua.
First of all, learn to use the command line so you can see the errors (on Windows that would be cmd.exe).
Second, change the second line to require("operations"). The way you did it the interpreter expects a directory operations with an underlying script lua.lua.

Passing variables into a function in Lua

I'm new to Lua, so (naturally) I got stuck at the first thing I tried to program. I'm working with an example script provided with the Corona Developer package. Here's a simplified version of the function (irrelevant material removed) I'm trying to call:
function new( imageSet, slideBackground, top, bottom )
function g:jumpToImage(num)
print(num)
local i = 0
print("jumpToImage")
print("#images", #images)
for i = 1, #images do
if i < num then
images[i].x = -screenW*.5;
elseif i > num then
images[i].x = screenW*1.5 + pad
else
images[i].x = screenW*.5 - pad
end
end
imgNum = num
initImage(imgNum)
end
end
If I try to call that function like this:
local test = slideView.new( myImages )
test.jumpToImage(2)
I get this error:
attempt to compare number with nil
at line 225. It would seem that "num" is not getting passed into the function. Why is this?
Where are you declaring g? You're adding a method to g, which doesn't exist (as a local). Then you're never returning g either. But most likely those were just copying errors or something. The real error is probably the notation that you're using to call test:jumpToImage.
You declare g:jumpToImage(num). That colon there means that the first argument should be treated as self. So really, your function is g.jumpToImage(self, num)
Later, you call it as test.jumpToImage(2). That makes the actual arguments of self be 2 and num be nil. What you want to do is test:jumpToImage(2). The colon there makes the expression expand to test.jumpToImage(test, 2)
Take a look at this page for an explanation of Lua's : syntax.