while using FMINCON can we pass matrices as arguments while using calling objective function saved as seperate file
4 views (last 30 days)
Show older comments
Krishna prasad K
on 20 Feb 2017
Commented: Krishna prasad K
on 20 Feb 2017
I'm using FMINCON . I saved my objective function in a seperate file. can i pass matrices as arguments while calling the objective function from main program.? if yes can i access the individual elements of the matrix?
call from main program is given below
[x,fval]=fmincon(@(x)fun(x,i,EC,PVpow,Pabrmp,Pplc,Psm,V1ref,k),x0,A,b,Aeq,beq,lb,ub,@(x)nonlcon(x,i,SOC1,PVpow,Pabrmp,Pplc,Psm,V1ref,k));
here PVpow,Pabrmp,Psm,Pplc are matrices
0 Comments
Accepted Answer
John D'Errico
on 20 Feb 2017
Yes. You can pass in any arguments you wish, matrices or not.
If you can pass them into a function, why would you think you cannot access individual elements of those matrices? Of course you can.
It seems apparent that you hd a problem, because otherwise, this question makes little sense. But if you got an error, then show it.
The function handle that you show:
@(x)fun(x,i,EC,PVpow,Pabrmp,Pplc,Psm,V1ref,k),
encapsulates the current value of those variables from the caller workspace, passing them into fun. fun can use those arguments in any way you wish.
3 Comments
John D'Errico
on 20 Feb 2017
Edited: John D'Errico
on 20 Feb 2017
Aw, give me a break! :) I can't read that pic without a microscope. :) :) I'm not old. Just age challenged.
The error message suggests what you did.
"Undefined function 'mtimes' for input arguments of type 'cell'."
So, one or more of those "arrays" is actually a cell array. I don't know which one, because there are a lot of multiplies in the line that had the error.
The point is though, you cannot multiply cell arrays. So lets try an example to show you what happens.
C = {1 2 3 4 5}
C =
1×5 cell array
[1] [2] [3] [4] [5]
C(1)*2
Undefined operator '*' for input arguments of type 'cell'.
The problem is, C(1) is still a cell array. I can extract that element though. So, this will work:
C{1}*2
ans =
2
Why does this happen?
C(1)
ans =
cell
[1]
C{1}
ans =
1
Because when you index a cell array with round parens, the result is another cell array. When you use curly braces, the result will be extracted from its cell array form.
You can also extract the elements of a cell array into a regular flat array using tools like cell2mat:
cell2mat(C)
ans =
1 2 3 4 5
D = cell2mat(C)
D =
1 2 3 4 5
D*pi
ans =
3.1416 6.2832 9.4248 12.566 15.708
More Answers (1)
See Also
Categories
Find more on Operators and Elementary Operations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!