MATLAB: Calling .m files in a loop - loops

How do I call 3 MATLAB .m files in a loop and display the results in sequence?

Another option (in addition to Amro's) is to use function handles:
fileList = {#file1 #file2 #file3}; % A cell array of function handles
for iFile = 1:numel(fileList)
fileList{iFile}(); % Evaluate the function handle
pause % Wait for a keypress to continue
end
You can call a function using its handle as I did above or using the function FEVAL. If you have a function name in a string, you can use the function STR2FUNC to convert it to a function handle (assuming it isn't a nested function, which requires the function handle constructor #). The following example illustrates each of these alternatives:
fileList = {str2func('file1') str2func('file2') str2func('file3')};
for iFile = 1:numel(fileList)
feval(fileList{iFile}); % Evaluate the function handle
pause % Wait for a keypress to continue
end
How do the two answers differ?
You may be wondering what the difference is between my answer (using function handles) and Amro's (using strings). For very simple cases, you would likely see no difference. However, you can run into more complicated scoping and function precedence issues if you use strings for the function names and evaluate them with EVAL. Here's an example to illustrate...
Let's say we have two m-files:
fcnA.m
function fcnA
disp('I am an m-file!');
end
fcnB.m
function fcnB(inFcn)
switch class(inFcn) % Check the data type of inFcn...
case 'char' % ...and do this if it is a string...
eval(inFcn);
case 'function_handle' % ...or this if it is a function handle
inFcn();
end
end
function fcnA % A subfunction in fcnB.m
disp('I am a subfunction!');
end
The function fcnB is designed to take either a function name or a function handle and evaluate it. By an unfortunate coincidence (or maybe intentionally) there is a subfunction in fcnB.m that is also called fcnA. What happens when we call fcnB in two different ways?
>> fcnB('fcnA') % Pass a string with the function name
I am a subfunction!
>> fcnB(#fcnA) % Pass a function handle
I am an m-file!
Notice that passing the function name as a string causes the subfunction fcnA to be evaluated. This is because at the time that EVAL is called the subfunction fcnA has the highest function precedence of all the functions named fcnA. In contrast, passing a function handle causes the m-file fcnA to be called instead. This is because the function handle is created first, then passed to fcnB as an argument. The m-file fcnA is the only one in scope (i.e. the only one that can be called) outside of fcnB, and is thus the one the function handle is tied to.
In general, I prefer to use function handles because I feel it gives me more control over which specific function is being called, thus avoiding unexpected behavior as in the above example.

Assuming that your files are scripts containing the plotting commands, you can do the following:
mfiles = {'file1' 'file2' 'file3'};
for i=1:length(mfiles)
eval( mfiles{i} );
pause
end
where for example, we have:
file1.m
x = 0:0.1:2*pi;
plot(x, sin(x))

Related

How to use an array of functions in Swift

I have read all the posts I can find here about arrays of functions - great you can do it. I figured. But none of the posts show practically how to use them (at least not what I'm trying to do). Here's what I want - they can all take the same args, but that's not a requirement.
This article is close, and will allow me to loop through to execute each function (which meets the first goal).
https://stackoverflow.com/a/24447484/11114752
But... what if I want to execute a single function by reference?
In other words, how to call just the referenced Arity2 function - for example:
// None of these work (with or without the parameter labels)
funcs.Arity2(n: 2, S: "Fred) // value of type [MyFuncs] has no member .Arity2
funcs[Arity2](n: 2, S: "Fred") // no exact matches to call in subscript
funcs[.Arity2](n: 2, S: "Fred") // Cannot call value of non-function type...
let fn = funcs.first(where: { a whole ton of permutations here to try to match Arity2 }) -- a whole lotta frustrating nope...
Help, please! Nothing I've tried works. The pre-compiler just goes in circles making suggestions that don't pan out and it will not compile.
EDIT:
The reason for the array in the first place is that I'm going to have a quite a few functions, and I don't know what they all are in advance. Essentially, I want a plugin type of architecture. Where I can add to the list of functions (ideally within an extension of the class, but that's another problem..) and not change the processing loop that executes each function in order.
I assume you need something like
_ = funcs.first {
if case let MyFuncs.Arity2(f) = $0 {
f(2, "Fred")
return true
}
return false
}
It can be achieved in a much simpler way if you know the position of the function in the array.
Assuming you have:
func someFunc(n: Int, s: String) {
print("call \(n) \(s)")
}
var funcs = [MyFuncs.Arity2(someFunc)]
you can do:
if case .Arity2(let f) = funcs.first {
f(2, "Fred")
}
By replacing funcs.first with funcs[i] you can access the i-th index (first make sure it does exist).

I'm studying recursion functions in C for the very first time. I tried to debug the function below and it's all clear except the index grow of n

int minimum(int *p,int n){
if (n==1)
return *(p+0);
int m = minimum(p,n-1);
if (m<*(p+(n-1)))
return m;
return *(p+(n-1));
}
The function checks all the values of an array and it returns the lowest value.
for example A[n]={1,2,3,4,5} it returns 1
considering n = 5 for example during the execution n goes from 5 to 1 until it goes into the first if ( if (n==1) ) and it returns the value of the first cell of the array p . After the first recall of the function the function itself keeps going ofc and it goes to the next if --> if (m<*(p+(n-1)))
Alright if i now check the n value it is 2 and then 3 and 4 and 5 so it reaches the end of the array controllying if there's a value lower than the previous one.
I do understand why n goes from 5 to 1 , but how does it goes from 1 to 5?? How the value of n grows if there's no increase ? i tested the function with a random array and it works completely fine .
Updated What i understood by your answers is this :
Ok so basically it's not 1 function at work but 5 (ideally tho) and everytime the cycle returns something it's like one of the function can stop working and focus on the new function with the new value (returning the value in base of the code) . So basically when n is equal 1 the function returns *(p+0). Once the cycle of the function with n=1 ends with the return , the cycle-function with n=2 starts working with the new value and so on . Is that right?
Each recursive function call has its own n. The calling level's n isn't affected by the changes made at the lower recursive calls. So when the lower call returns, the caller's n is unmodified.
The n variable never change because each function call has its ows n... you are seeing a 'increasing of n' because you have to remember that a function call also do a rollback from the last, where n==1, to the first, where n==5, so if you print n after the recursive call, you will see 1->2->3->4->5 just because the function are doing a rollback of the recursive calls
Every time a function is called, a part of the computer's memory (RAM) is reserved for the instance of the called function. The part of the memory is called a stack and the portion reserved for the function instance is called a stack frame.
Instance-specific data (like function parameters and variables) are stored in the stack frame.
When another function is called (or even the same function again), a new stack frame is created and the new function instance stores its data there. When it returns, the original function instance resumes execution (note that there is more code after the int m = minimum(p,n-1); line, which needs to get executed at some point) in its own stack frame, retaining the values of the parameters and variables.
You are mixing up multiple different n variables. Variable n == 5 still exists when variable n == 4 is created, and ceases to exist after n == 4 is destroyed.
As with every function call, the variables for the called function are created on entry and deleted on return. So, each time the recursive function is invoked, all its local variables are created again for that invocation. They are not shared between different invocations just because the function happens to be the same.
For a variable to be shared between all the invocations of a function call, it must be static, but function arguments like n can not be static.

How to define input types in Matlab Coder for a function that has a varying number of input?

I have a function let's say sq_dist(). This function can be called like this sq_dist(a,b) or sq_dist(a). This function includes slow operations and thus I am trying to make a Mex version of it hoping that it will run faster. I am using the Matlab Coder GUI to do so. In order to define input types (in the define input screen) i use a function that calls sq_dist(a,b) and sq_dist(a) to automatically determine input. This gives me an error: Error determining type for input sq_dist:b. Index exceeds matrix dimensions. Here is my function:
n = 50;
dim = 50;
a = rand(n, dim);
b = rand(n, dim);
u = sq_dist(a, b);
v = sq_dist(a);
So, since sq_dist can be called in different ways I am not sure how to define its input in the Coder.
If i manually set the input to double :inf x :inf for a and b the mex file is compiled but i get a runtime error: Function 'sq_dist' called with wrong number of arguments: expected 2, received 1.
In short, you cannot do what you want to do (with current version 2016a) for the top-level function - this has to have a defined number of inputs and outputs. Even if you use the 'varargin' parameter in the function definition, MATLAB Coder will generate the function with a fixed number of inputs based on the example arguments you provide.
If you have a particular function that has a variable number of input arguments, you can put a wrapper function (with a fixed number of input arguments) around the outside, and make the wrapper the top-level function.
Rules here:
http://uk.mathworks.com/help/simulink/ug/rules-for-using-variable-length-argument-lists-for-code-generation.html

indexed object dot notation method gives scalar property

I'm seeing an issue when I try and reference an object property after having used a dot notation to apply a method.
it only occurs when I try to index the initial object
classdef myclassexample
properties
data
end
methods
function obj = procData(obj)
if numel(obj)>1
for i = 1:numel(obj)
obj(i) = obj(i).procData;
end
return
end
%do some processing
obj.data = abs(obj.data);
end
end
end
then assigning the following
A = myclassexample;
A(1).data= - -1;
A(2).data = -2;
when calling the whole array and collecting the property data it works fine
[A.procData.data]
if i try and index A then i only get a scalar out
[A([1 2]).procData.data]
even though it seems to do fine without the property call
B = A([1 2]).procData;
[B.data]
any ideas?
I would definitely call this a bug in the parser; A bug because it did not throw an error to begin with, and instead allowed you to write: obj.method.prop in the first place!
The fact that MATLAB crashed in some variations of this syntax is a serious bug, and should definitely be reported to MathWorks.
Now the general rule in MATLAB is that you should not "index into a result" directly. Instead, you should first save the result into a variable, and then index into that variable.
This fact is clear if you use the form func(obj) rather than obj.func() to invoke member methods for objects (dot-notation vs. function notation):
>> A = MyClass;
>> A.procData.data % or A.procData().data
ans =
[]
>> procData(A).data
Undefined variable "procData" or class "procData".
Instead, as you noted, you should use:
>> B = procData(A): % or: B = A.pocData;
>> [B.data]
FWIW, this is also what happens when working with plain structures and regular functions (as opposed to OOP objects and member functions), as you cannot index into the result of a function call anyway. Example:
% a function that works on structure scalar/arrays
function s = procStruct(s)
if numel(s) > 1
for i=1:numel(s)
s(i) = procStruct(s(i));
end
else
s.data = abs(s.data);
end
end
Then all the following calls will throw errors (as they should):
% 1x2 struct array
>> s = struct('data',{1 -2});
>> procStruct(s).data
Undefined variable "procStruct" or class "procStruct".
>> procStruct(s([1 2])).data
Undefined variable "procStruct" or class "procStruct".
>> feval('procStruct',s).data
Undefined variable "feval" or class "feval".
>> f=#procStruct; f(s([1 2])).data
Improper index matrix reference.
You might be asking yourself why they decided to not allow such syntax. Well it turns out there is a good reason why MATLAB does not allow indexing into a function call (without having to introduce a temporary variable that is), be it dot-indexing or subscript-indexing.
Take the following function for example:
function x = f(n)
if nargin == 0, n=3; end
x = magic(n);
end
If we allowed indexing into a function call, then there would be an ambiguity in how to interpret the following call f(4):
should it be interpreted as: f()(4) (that is call function with no arguments, then index into the resulting matrix using linear indexing to get the 4th element)
or should it interpreted as: f(4) (call the function with one argument being n=4, and return the matrix magic(4))
This confusion is caused by several things in the MATLAB syntax:
it allows calling function with no arguments simply by their name, without requiring the parentheses. If there is a function f.m, you can call it as either f or f(). This makes parsing M-code harder, because it is not clear whether tokens are variables or functions.
parentheses are used for both matrix indexing as well as function calls. So if a token x represents a variable, we use the syntax x(1,2) as indexing into the matrix. At the same time if x is the name of a function, then x(1,2) is used to call the function with two arguments.
Another point of confusion is comma-separated lists and functions that return multiple outputs. Example:
>> [mx,idx] = max(magic(3))
mx =
8 9 7
idx =
1 3 2
>> [mx,idx] = max(magic(3))(4) % now what?
Should we return the 4th element of each output variables from MAX, or 4th element from only the first output argument along with the full second output? What about when the function returns outputs of different sizes?
All of this still applies to the other types of indexing: f()(3)/f(3), f().x/f.x, f(){3}/f{3}.
Because of this, MathWorks decided avoid all the above confusion and simply not allow directly indexing into results. Unfortunately they limited the syntax in the process. Octave for example has no such restriction (you can write magic(4)(1,2)), but then again the new OOP system is still in the process of being developed, so I don't know how Octave deals with such cases.
For those interested, this reminds me of another similar bug with regards to packages and classes and directly indexing to get a property. The results were different whether you called it from the command prompt, from a script, or from a M-file function...

Making outputs from an array in Matlab?

I have an array of 20 items long and I would like to make them an output so I can input it into another program.
pos = [0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,0.5,]
I would like to use this as inputs for another program
function [lowest1, lowest2, highest1, highest2, pos(1), pos(2),... pos(20)]
I tried this and it does not work is there another way to do this?
I'm a little confused why you'd want to do that. Why would you want 20 outputs when you could just return pos as a single output containing 20 elements?
However, that said, you can use the specially named variable varargout as the last output variable, and assign a cell to it, and the elements of the cell will be expanded into outputs of the function. Here's an example:
function [lowest1, lowest2, highest1, highest2, varargout] = myfun
% First set lowest1, lowest2, highest1, highest2, and pos here, then:
varargout = num2cell(pos);
If what you're trying to do is re-arrange your array to pass it to another Matlab function, here it is.
As one variable:
s=unique(pos);
q=[s(1) s(2) s(end-1) s(end) pos];
otherFunction(q);
As 24 variables:
s=unique(pos); otherFunction(s(1), s(2), s(end-1), s(end), pos(1), pos(2), pos(3), pos(4), pos(5), pos(6), pos(7), pos(8), pos(9), pos(10), pos(11), pos(12), pos(13), pos(14), pos(15), pos(16), pos(17), pos(18), pos(19), pos(20));
I strongly recommend the first alternative.
Here are two examples of how to work with this single variable. You can still access all of its parts.
Example 1: Take the mean of all of its parts.
function otherFunction(varargin)
myVar=cell2mat(varargin);
mean(myVar)
end
Example 2: Separate the variable into its component parts. In our case creates 24 variables named 'var1' to 'var24' in your workspace.
function otherFunction(varargin)
for i=1:nargin,
assignin('base',['var' num2str(i)],varargin{i});
end
end
Hope this helps.
Consider using a structure in order to return that many values from a function. Carefully chosen field names make the "return value" self declarative.
function s = sab(a,b)
s.a = a;
s.b = b;

Resources