I would like Matlab to return all the outputs from a variable input function. For instance,
[varargout]=cpd_intersect(varargin{:});
This only returns the last output but I know the function is defined to give multiple outputs.
Instead of defining dummy variables A, B , C etc in [A,B,C...]=pd_intersect(varargin{:}). I would like something like a cell to store all the output values based on the input number of values. I hope this makes sense. Many thanks in advance.
I know this is late, but I think this is what you want:
function [varargout] = myfun(f, varargin)
% apply f to args, and return all its outputs
[ x{1:nargout(f)} ] = f(varargin{:}); % capture all outputs into a cell array
varargout = x; % x{:} now contains the outputs of f
The insight here is that
NARGOUT can operate on functions and returns their maximum number of outputs
using [ X{1:2} ] = ...on the left hand side when X is undefined, is equivalent to doing [ X{1} X{2} ] = ..., and can capture 2 separate outputs into individual variables.
Two points to note:
this works for anonymous functions too! e.g. #(x)eig(x)
it won't work for functions that use varargout, i.e. functions with truly variable numbers of outputs. If this is the case then there should be a way to calculate how many outputs you are going to have, e.g. using nargin.
PS I learnt this from #gnovice, If a MATLAB function returns a variable number of values, how can I get all of them as a cell array?
You can do this by returning a cell array
I see you cannot force a variable comma separated output list in Matlab. Pity. It would be useful. It seems I have to explicitly assign each output. This sucks since I do not know beforehand the number of outputs I will get.
Related
To process data in MATLAB I have to execute a certain function, let's call it function(). Since there is much data to be processed, like large array Time or Voltage (but many more) I execute those one by one like this:
TimeNew = function(Time);
VoltageNew = function(Voltage);
... etc
So this is done around 10 times. Moreover, I have to do such a thing multiple times, resulting in around 30 lines of code which all do the same thing but to a different variable.
Is there a way to optimize this? I am using the most recent version of MATLAB (2015b) and have all toolboxes installed.
A possible solution could be to store the input array into a struct, them use that struct as input of the function.
In the function you can identify the number and content of each field by using fieldnames and getfiled built-in function.
The function could return a structure as output whose names can be made the same as the ones of the input struct.
In the example below, three arrays are generated and the function siply compute their square.
var_1=1:10;
var_2=11:20;
var_3=21:30;
str_in=struct('var_1',var_1,'var_2',var_2,'var_3',var_3)
str_out=my_function(str_in)
The function
function [str_out]=my_function(str_in)
f_names=fieldnames(str_in)
n_fields=length(f_names);
for i=1:n_fields
x=getfield(str_in,f_names{i})
str_out.(f_names{i})=x.^2;
end
Hope this helps.
Qapla'
You could try cellfun
allResultsAsACell = cellfun(#function, {Time,Voltage,...,varN});
This is equivalent to
allResultsAsACell{1} = function(Time);
allResultsAsACell{2} = function(Voltage);
...
allResultsAsACell{N} = function{VarN};
The issue is just matching up the indices with the values. I'm sure you could code those in as well if you needed (e.g. timeInd = 1; voltageInd =2; ...)
To see more on the cellfun method, type
help cellfun
into your MATLAB terminal.
I am trying to understand the following commands of a MATLAB script :
global operatorObj
calcEVR_handles = operatorObj.calcEVR_handles;
m = operatorObj.nInputs
E = zeros(m,1);
V = zeros(m,1);
R = zeros(m,m);
for i=1:m
[E(i), V(i), R(i,i)] = calcEVR_handles{i}(t,x);
end
What can calcEVR_handles be, if t is a float and x is a vector?
calcEVR_handles (to me) looks like a cell array where each element is a handle to a function. Each element in calcEVR_handles is an anonymous function that takes in a single value t and a single vector x. As such, by doing calcEVR_handles{i}, you would access the corresponding function stored at the ith element in the cell array. Once you have access, you then pass your parameters to this function and it gives you those three outputs.
To show you an example of this working, consider the following cell array that works similarly to calcEVR_handles.
calcCellFunc = {#sin, #cos, #tan};
This is a three element cell array, where each element is a handle to a function. The # is a special character in MATLAB that denotes that you are creating a handle to a function. It's also used to create anonymous functions, but let's shelve that for this answer. You can read more about it here if you want to delve into more detail regarding this.
Back to our cell array of handles, we will make handles for sin, cos and tan. You can then iterate over your cell array by accessing the function you want by calcCellFunc{idx} where idx is the element you want in the cell array. This will ultimately give you the function stored at index idx. Once you do that, you can then call the function and specify whatever inputs you want (or none if it doesn't take any inputs). Here's a quick example for you. Let's create a random 5 x 5 matrix, and run through each function with this matrix serving as the input. We then take each of these outputs and store them into a corresponding slot in an output cell array. As such:
rng(123); %// Set seed for reproducibility
M = rand(5);
calcCellFunc = {#sin, #cos, #tan};
out = cell(1, numel(calcCellFunc)); %// To store the results for each function
for idx = 1 : numel(calcCellFunc)
out{idx} = calcCellFunc{idx}(M); %// Get the function, then pass
%// the matrix M to it
end
If you want to make things clear, you could split up the out statement to this instead:
func = calcCellFunc{idx}; %// Get access to the function
out{idx} = func(M); %// Pass M to this function
If you're new to handles / anonymous functions, you should probably use the above code first to make it explicitly clear on what MATLAB is doing. You are first getting access to the function you want that is stored in the cell array, and then you pass your arguments to this function.
If we display the output, we get:
>> celldisp(out)
out{1} =
0.6415 0.4106 0.3365 0.6728 0.5927
0.2823 0.8309 0.6662 0.1815 0.7509
0.2249 0.6325 0.4246 0.1746 0.6627
0.5238 0.4626 0.0596 0.5069 0.5737
0.6590 0.3821 0.3876 0.5071 0.6612
out{2} =
0.7671 0.9118 0.9417 0.7398 0.8054
0.9593 0.5564 0.7458 0.9834 0.6604
0.9744 0.7745 0.9054 0.9846 0.7489
0.8518 0.8866 0.9982 0.8620 0.8191
0.7522 0.9241 0.9218 0.8619 0.7502
out{3} =
0.8363 0.4503 0.3573 0.9094 0.7359
0.2942 1.4934 0.8932 0.1845 1.1370
0.2308 0.8167 0.4690 0.1773 0.8850
0.6149 0.5218 0.0597 0.5880 0.7004
0.8761 0.4135 0.4205 0.5884 0.8814
The first element of the output cell array has the output when you pass M to sin, the second when you pass M to cos, and the third when you pass M to tan.
So the next question you're asking... why is this useful?
Point #1 - Nix the copying and pasting
This kind of code writing is very useful because if you want to use the same inputs and supply them to many different functions, we would naturally be inclined to do some copying and pasting. Take each of your function names, and create a single line for each. Each line would call the corresponding function you want, followed by the input arguments. This can become quite tedious, and so one smart way to do it would be to place your function name as a handle into a cell array, and to write one for loop that goes over all of the functions dynamically. You could even explore cellfun and escape using the for loop to iterate over all of the function handles too, but I'll leave that for you to read up on.
In this way, you have very maintainable code and if you want to remove functions that don't need to be run, just remove the handles from the cell array rather than scrolling down to where the line that invokes this function is located and removing that.
This is actually a very common technique in computer science / software engineering in general. In fact, this is actually quite close to what are known as function pointers. This is MATLAB's cheap way of doing it, but the logic behind this is essentially the same.
Point #2 - Higher Order Functions
Another way this is useful is if you have a function where one (or more than one!) of the inputs is a function, and you also specify inputs into this function as additional parameters to this function. This is what is known as a higher order function. The outputs would be based on using this input function, and the additional inputs you specify to it and the outputs are based on using this input function and the inputs you specify for this function.
One very good example is the fzero function in MATLAB. The goal is to find the root of a non-linear function, and the first parameter is a handle to a function that you specify. The base behaviour behind how fzero works is the same no matter what the function is. All you have to do is specify the function you want to solve and the initial guess of where you think this root is.
All in all, anonymous functions are very useful.
Suppose I have a function that gives out unknown number of output arguments (it depends on input,thus change through the loops). How to get all of them?
nargout doesn't help as the function uses varargout (the result is -1)
And of course I can't rewrite the function, otherwise the question wouldn't arise :- )
Well, thanks to all partisipated in discussion. Summing up, it seems the problem has no general solution, because MatLab itself estimates the number of desired outputs before the function call to use inside it. Three cases can be pointed out though:
1) The funcrion doesn't have varargout in definition, thus nOut=nargout(#fcn) returns positive number.
Then nOut is an actual number of outputs and we can use a cell array and a column list trick.
X=cell(1,nOut);
[X{:}]=fcn(inputs);
2) The funcrion has varargout in definition, thus nOut=nargout(#fcn) returns negative number. However some correlation with inputs can be found (like length(varargin)=length(varargout)).
Then we can calculate the resulting nOut from inputs and perform the above column list trick.
3) You know the fcn developer.
Ask him fot assistance. For example to make the function's output to be a cell array.
One of ways I usually use in this case is to store all outputs in a cell array inside the function. Getting the cell array outside the function's body, you might investigate its length and other properties.
Here is how you could deal with the problem in general. I didn't mention this solution earlier because... it is horrible.
Suppose a function can have 1 or 2 output arguments:
try
[a, b] = f(x)
catch
a = f(x)
end
Of course it is possible to do this for any number of output arguments, but you really don't want to.
I am new to matlab. This might be a silly question.
The problem says:
Write a function sum_var which takes variable number of scalar inputs & returns their sum
E.g.
sum_var(2,4,6)
ans =
16
I tried varargin,nargin however i cant manipulate those commands to get a desired output.
If you want to have a function that takes several scalar inputs and give you their sum, then do the following:
function result = sum_var(varargin)
result = sum(cell2mat(varargin));
end
The problem you have is that varargin is a cell array and you have to transform it to a matrix array (using cell2mat()) before using the sum() function on it.
I have a system of equations contained in an anonymous equation. Instead of defining all of the equations when i create the function, I would like to add one in each step of a for loop. Is this possible?
I suppose if you have a linear set of equations, you can construct it using a matrix, then you're free to include new operations by adding rows and columns to the matrix and/or its accompanying right hand side vector.
If you're really trying to use anonymous functions, say if your functions are non-linear, then I would suggest you to look into arrays of anonymous functions. For example,
A = cell(3,1); % Preallocate a 3 by 1 cell array
for ii = 1:3
A{ii} = #(x) x^2+ii; % Fill up the array with anonymous functions
end
Now if you check what's contained in cell array 'A',
A = #(x)x^2+ii
#(x)x^2+ii
#(x)x^2+ii
Don't worry about the display of 'ii' instead of the actual number of the loop variable as we gave it earlier, MATLAB has internally replaced them with those values. Changing 'ii' in the current function scope will also not affect their values in 'A' either. Thus,
A{1}(2) = 5, A{2}(2) = 6 and A{3}(2) = 7
If you're not familiar with cell arrays, you can read up on its usage here.
Again, what you're trying to achieve might be different. I hope this works for you.