Matlab: Abort function call with Strg+C but KEEP return value - function

I have a function in matlab with something like this:
function [ out ] = myFunc(arg1, arg2)
times = [];
for i = 1:arg1
tic
% do some long calculations
times = [times; toc];
end
% Return
out = times;
end
I want to abort the running function now but keep the values of times which are currently already taken. How to do it? When I press strg+c, I simply loose it because it's only a local function variable which is deleted when the function leaves the scope...
Thanks!

Simplest solution would be to turn it from a function to a script, where times would no longer be a local variable.
The more elegant solution would be to save the times variable to a .mat file within the loop. Depending on the time per iteration, you could do this on every loop, or once every ten loops, etc.

Couldn't you use persistent variables to solve your problem, e.g.
function [ out ] = myFunc(arg1, arg2)
persistent times
if nargin == 0
out = times;
return;
end;
times = [];
for i = 1:arg1
tic
% do some long calculations
times = [times; toc];
end
% Return
out = times;
end
I'm not sure whether persistent variables are cleared upon Ctrl-C, but I don't think it should be the case. What this should do: if you supply arguments, it will run as before. When you omit all arguments however, the last value of times should be returned.

onCleanup functions still fire in the presence of CTRL-C, however I don't think that's really going to help because it will be hard for you to connect the value you want to the onCleanup function handle (there are some tricky variable lifetime issues here). You may have more luck using a MATLAB handle object to track your value. For example
x = containers.Map(); x('Value') = [];
myFcn(x); % updates x('Value')
% CTRL-C
x('Value') % contains latest value

Another possible solution is to use the assignin function to send the data to your workspace on each iteration. e.g.
function [ out ] = myFunc(arg1, arg2)
times = [];
for i = 1:arg1
tic
% do some long calculations
times = [times; toc];
% copy the variable to the base workspace
assignin('base', 'thelasttimes', times)
end
% Return
out = times;
end

Related

How do I set a function to a variable in MATLAB

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

Matlab fminsearch options/restrictions

I have this function in Matlab which is supposed to find the smallest value possible for minValuePossible, by varying the two initial set values of inValues. How can I set the fmin search function to NOT try negative values while trying to find the minimum? Also how can I set the number of different variations the fminsearch function performs while trying to find the minimum? Because currently it tries somewhere around 20 different combinations of the two inValues and then completes. Maybe define the amount by which it changes each value? How would I do that?
function Valueminimiser
inValues = [50,50];
minValuePossible = fminsearch(#minimiser, inValues);
function result = minimiser(inValues)
x=inValues(1);
y=inValues(2);
RunMode = 2;
ValueOne = x;
ValueTwo = y;
[maxSCRAout] = main(RunMode,ValueOne,ValueTwo);
result = minValuePossible;
end
end
How can I set the fmin search function to NOT try negative values while trying to find the minimum?
Add the constrains of the values of your minimiser function at its beginning. If you meet this constrains then return a huge function value of minimizer. This will prevent fminsearch consider numbers which are not in your interest:
function result = minimiser(inValues)
if (sum(inValues < 0) > 1) % check if there is any negative number in input variable
result = hugeValue; % give a big value to the result
return; % return to fminsearch - do not execute the rest of the code
end
x=inValues(1);
y=inValues(2);
RunMode = 2;
ValueOne = x;
ValueTwo = y;
[maxSCRAout] = main(RunMode,ValueOne,ValueTwo);
result = minValuePossible;
Also how can I set the number of different variations the fminsearch function performs while trying to find the minimum?
You can define options of fminsearch by using optimset function. The parameter of optimset 'MaxFunEvals' is the maximum number of evaluations -- notice that this cout even the values you constrained, so maybe setting 'TolX' as advised by #slayton might be better if you are concerned about the accuarcy.
options = optimset('MaxFunEvals',numberOfVariations);
minValuePossible = fminsearch(#minimiser, inValues,options);
The docs for fminsearch don't describe a way to restrict the domain of the function you want to minimize.
If you want to restrict the range to all non-negative numbers then you can simply wrap your function in a call to abs, depending on the syntax .
minValuePossible = fminsearch( #(x)(minimiser( abs(x) ) ), inValues);
If you are worried about it constantly converging to the same minima then try a variety of different initial values.
Lastly you can alter the termination tolerances for X and minValuePossible using the TolX and TolFun input parameters. This is done with standard param value syntax: function(...., 'Param', value)
fminsearch( #(x)(minimiser(abs(x))), inValues, 'TolX', x_tolerance);

MATLAB How to pass an Array from my base workspace to a function

I have been on a few forum posts now reading through trying to figure this out but I can't seem to crack it. To summarise my function I have 2 arrays searchDates and searchIds. Now all I want to do is do a comparison on the size of one of the elements to the other array and this is the code I have so far but I don't know how to carry over searchDates and searchIds
function a = compare(userNum)
if size(searchDates{1,userNum},2) == size(searchIds{1,userNum},2)
x = true
else x = false
end
TL;DR I just need to know how to pass from my BASE WORKSPACE to my FUNCTION WORKSPACE the two arrays from above.
Cheers!
You can rewrite your function so that you can directly pass the arrays:
function a = compare(userNum,searchDates,searchIds)
if size(searchDates{1,userNum},2) == size(searchIds{1,userNum},2)
x = true
else x = false
end
then call compare with your workspace variables in the 2nd and 3rd argument.
If for some reason you need compare to only have one argument, you can create an anonymous function in your workspace by using the above function compare and writing:
anon_compare = #(userNum) compare(userNum,searchDates,searchIds)
Provided searchDAtes and searchIds are in your workspace, you will now have the function anon_compare, which you can use directly as anon_compare(foo).
For more on anonymous functions (an important aspect of several MATLAB programming techniques) you can read this post.

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.