equivalent of "apply" in Octave / Matlab? - matlab

I have a function in Octave / Matlab such as this (the real one is much, much more complicated)
function result = foo (x, y, z)
result = x + y + z;
endfunction
The normal way to invoke the function is as follows:
foo (1, 2, 3);
but I'd like to apply it to arguments packaged in an array like this:
myStuff = [1, 2, 3];
apply (foo, myStuff);
or
foo (myStuff);
I haven't been able to find the syntax needed for such an invocation in the documentation or on Google.

This is possible if you place your arguments in a cell array and use the comma-separated list operator :.
For instance:
c = {x, y, z};
foo(c{:});
is equivalent to:
foo(x,y,z);
Best,

Related

Matlab: passing more arguments to `nlinfit` function

I am in interested in passing extra arguments to nlinfit function in Matlab
beta = nlinfit(X,Y,modelfun,beta0)
and let the modelfun is
function y = modelfun(beta, c, X)
y = beta(1)*x.^(beta2) + c;
My interest is estimate beta and also to provide c externally. X and Y have their obvious meanings.
Can it be done?
If c is a value generated before you call nlinfit (i.e. its value is fixed while nlinfit is running), then you can use an anonymous function wrapper to pass the extra parameter like so:
beta = nlinfit(X, Y, #(beta, X) modelfun(beta, c, X), beta0);

Macro to generate element-wise methods

I see myself writing this pattern again and again, where a function can take an entity E or a iterator over Es and apply elementwise. eg:- an index or a vector. A column or a matrix. I was wondering if there is a macro so that I need not define multiple methods. I am looking for a julian way of doing this.
In the simplified version of my use case below, compare getrow which is naturally overloaded to work on ints or slices with innerprod that needs to be redefined for Vectors and Matrixes.
type Mat{T<:Number}
data::Matrix{T}
end
getrow{T}(m::Mat{T}, i=size(m)[1]) = m.data[i, :]
innerprod{T}(m::Mat{T}, v::Array{T}) = m.data*v
innerprod{T}(m::Mat{T}, vv::Matrix{T}) = mapslices(v->innerprod(m, v), vv, 1)
m = Mat(rand(1:9, 2, 3))
v = rand(1:9, 3, 4)
f = innerprod(m, v[:,1])
g = innerprod(m, v)

Call functions with #() in MATLAB [duplicate]

This question already has answers here:
matlab to R: function calling and #
(2 answers)
Closed 8 years ago.
I'm trying to figure out what is the purpose of #(t) in the following code snippet:
[theta] = ...
fmincg (#(t)(lrCostFunction(t, X, (y == c), lambda)), ...
initial_theta, options);
lrCostFunction:
function [J, grad] = lrCostFunction(theta, X, y, lambda)
%LRCOSTFUNCTION Compute cost and gradient for logistic regression with
%regularization
% J = LRCOSTFUNCTION(theta, X, y, lambda) computes the cost of using
% theta as the parameter for regularized logistic regression and the
% gradient of the cost w.r.t. to the parameters.
and options:
options = optimset('GradObj', 'on', 'MaxIter', 50);
I'd appreciate some explanation. Thanks in advance
Let me answer your question focusing on anonymous function itself.
The following function, defined in a separate .m file
function y = foo(x, a, b)
y = x^(a-b);
end
is equivalent to defining an anonymous function in the main script
bar = #(x, a, b) x^(a-b);
When your main script calls function foo(5, 1, 2), Matlab searches in working directory, then reads and executes code within file foo.m. Contrarily, when you run a line bar(5, 1, 2), Matlab calls a "function handle" and treat it as a function (though its power is limited by a single line of code - you can't perform things like switch or for easily).
Sometimes we need to wrap some function into an easier-to-use one. Consider a case where we want to evaluate foo 1000 times, but only input x changes, while a and b remains same. It's of course OK to write foo(x, 1, 2) in the for loop, but you can also wrap the function before going into the loop.
a = 1;
b = 2;
foobar = #(x) foo(x, a, b);
When you call foobar(5), Matlab first invokes the function handle foobar, taking 5 as its only input. That function handle has one instruction: call another function (or function handle, if you define it as so) named foo. The arguments of foo are: x, which is defined when user calls foobar(x); a and b, which have been defined in the first place BEFORE the function handle definition code is executed.
In your case, fmincg only accepts, as its first argument, a function that only has one input argument. But lrCostFunction takes four. fmincg doesn't know how to treat x, y, or lambda (I don't either). So it's your job to wrap the cost function into the form that a general optimizer can understand. That also requires you assign x, y, c and lambda in advance.
What is it.
#(t) creates a function with argument t that calls your costFunction(t,X,y) so if you write
fmincg (#(t)(lrCostFunction(t, X, (y == c), lambda)), ...
initial_theta, options);
it will call your function lrCostFunction and pass the values
Why we need it
It allows us to use the built in optimization function provided by Octave (because MATLAB doesn't have fminc function AFAIK). So it takes your costFunction and Optimise it using the settings that you provide.
Optimization Settings
optimset('GradObj', 'on', 'MaxIter', 50); allows you to set the Optimization settings that are required for minimization problem as mentioned above.
All information is from Andrew NG classes. I hope it helps..
Correct me if I am wrong.

In Matlab why does cellfun(#size, x) not require UniformOutput False for non scalar values?

In Matlab you can do the following
x = {1:4, rand(3,3,3), 3};
[a, b, c] = cellfun(#size, x);
The above though not scalar output, does not require UniformOutput to be false.
If instead I have
x = {1:4, rand(3,3,3), 3};
[a,b,c] = cellfun(#(my_dummy_fun) [1, 2, 3], x); % GIVES ERROR
I get an error. How is this different than #size? Is there a way to get the same behavior for the custom function as for size?
thanks!
You where confused by size. Size allows a single output (vector) or multiple output arguments.
%three outputs
[a,b,c]=size(rand(3,3,3))
%one output
[x]=size(rand(3,3,3))
where x =[a,b,c]
You are successfully using size with three output arguments, but your function handle has only one output argument (which is a vector).
I don't know any possible syntax to directly define a anonymous function with multiple output arguments. To work around this, I wrote this small wrapper function:
function varargout=vec2nargout(in)
varargout=mat2cell(in(:),ones(1,nargout));
end
It allows:
[a,b,c] = cellfun(#(my_dummy_fun)vec2nargout([1,2,3]), x);

How to implement this function in mupad (MATLAB)

I want to implement the following function. But I dont know how to define a function over a set of variables such as mu(1), mu(2), mu(3),..., mu(c). c is a numeric symbol (i.e. it is a parameter of the function, but not an input value):
f := (mu(i), i=1..c) -> sum(mu(i)^2,i=1..c)
In other words, I want the symbolic form of f(MU)=norm(MU)^2, where MU is a vector of 1xc variables.
Thanks
EDIT:
In fact, I want to trace the following computation in mupad from Modeling Uncertainty with Fuzzy Logic: With Recent Theory and ....
I have also attached the picture of computation steps (of fuzzy c-means).
I'm not sure that I understand the question (how c can be a parameter, but not an input value?)
>> f = #(mu) sum(mu .^ 2); % applied on all elements
>> g = #(mu, c) sum(mu(1 : c) .^ 2); % applied on mu(1:c)
>> f(1:3)
ans =
14
>> g(1:10, 3)
ans =
14
f := mu -> _plus(mu[i]^2 $ i=1..nops(mu));
Call with a list:
f([1,2,3,4])
Or, to be able to invoke f(1,2,3,4):
f := () -> _plus(args(i)^2 $ i=1..args(0));