Rasmus Elbaek
Rasmus Elbaek

Reputation: 13

Matlab functions - how to capture vector outputs into a single variable?

I have a problem extracting the outputs of various functions and defining them as they are calculated. I would like to have a main document performing tasks like:

fcost(variables)

--> vector output f = vector output.

The exact code is as follows:

function fcost(hours,heatcost,slack1,slack2,realdata)


ncalc = 4 * hours;

P = zeros(ncalc*3*4,1);

if realdata == 2;

    SIN = sin((1:ncalc*4)/8)*0.5+0.7

    P(1:3:end) = SIN(1:ncalc*4);
    P(2:3:end) = slack1;
    P(3:3:end) = slack2;

else

    P(1:3:end) = heatcost;
    P(2:3:end) = slack1;
    P(3:3:end) = slack2;

end
P
format short
end

The problem is that the function only spits out the vector - and doesnt define anything for the main file to put to use.

Thanks in advance!

Upvotes: 0

Views: 50

Answers (1)

rayryeng
rayryeng

Reputation: 104555

The code that is written only displays the vector and doesn't return it. This is apparent by the function header of your code:

function fcost(hours,heatcost,slack1,slack2,realdata)

This declares a function fcost with various parameters, but it doesn't return anything. If you want to return P after calling fcost, you need to modify your function header to:

function P = fcost(hours,heatcost,slack1,slack2,realdata)

Now save this function to a file called fcost.m, then when it's time to use it, do:

P = fcost(hours, heatcost, slack1, slack2, realdata);

The output of fcost will be stored in P. Because you are now returning P, you probably want to remove the last two verbose statements of your code. Specifically, delete these two lines:

P
format short

Upvotes: 1

Related Questions