How to define a function whose number of outputs depend on an input parameter value?
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Saurabh Madankar
am 21 Mai 2024
Kommentiert: Saurabh Madankar
am 21 Mai 2024
Say for M = 4, I have a code below.
function [c,ceq] = Constraint(M)
c = [];
for i=1:M
ceq_{i} = i;
end
ceq = [ceq_{1} ceq_{2} ceq_{3} ceq_{4}];
end
My question is for bigger values of M, how do I define the last ceq so that I don't have to write each ceq_{i}'s individually?
0 Kommentare
Akzeptierte Antwort
Kunal Kandhari
am 21 Mai 2024
You can dynamically create and concatenate the elements of ceq based on the value of M. Here's how you can modify your function to achieve that:
function [c, ceq] = Constraint(M)
c = [];
ceq = [];
for i = 1:M
ceq = [ceq, i]; % Concatenate each element
end
end
With this modification, ceq will automatically adjust its size based on the value of M, eliminating the need to define each element individually.
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!