Output must be a column vector

I can't get this function to output a vector.
function dPdq = dPdq (t, y)
global Vd Tc Rv r_ar Qin p PI deltaq dPdq
A_weibe=5;
B_weibe=3;
R=8.314;
m=6;
PCI=2.772e7;
P=y;
q=t
Qs=340;
Qb=60;
for q=PI:(PI+deltaq)
% Volume
V(q)=Vd/(Tc-1)+(Vd/2)*(Rv+1-cos(q)-sqrt(Rv^2-(sin(q))^2));
% dVdq
dVdq(q)=(Vd/2)*sin(q)*(1+cos(q)*(Rv^2-(sin(q))^2)^-0.5);
if ((q>=Qs)&&(q<Qs+Qb))
F(q)=1-exp(-A_weibe*((q-Qs)/Qb)^B_weibe)
dFdq(q)=B_weibe*A_weibe/Qb*(1-F(q))*((q-Qs)/Qb)^(B_weibe-1)
dPdq(q)=-r_ar*(P/V(q))*dVdq(q)+(r_ar-1)*((Qin/V(q))*dFdq(q))
else
dPdq(q)=-r_ar*(P/V(q))*dVdq(q);
end
end
I tried simply callling:
dYdq(1)=dPdq %---- no success
dYdq(:)=dPdq(:) %----- no success
for i=1:400
dy(i,1)=dPdq(i);
end %------------------------no success
I have no ideas left, do you have any insights?

Antworten (1)

Guillaume
Guillaume am 21 Okt. 2019

0 Stimmen

It looks like your error message comes from an ODE solver. It's the ODE solver that calls your function, so it's unclear what you mean by "I tried simply calling..."
Anyway, if you get this error, the problem is not with the way the function is called, it's with the way the function constructs its outputs. It's currently constructing the outputs as row vector, whereas the calling code expects column vector.
The simplest way is to preallocate the outputs as column vectors. Outputs should be preallocated anyway and with preallocation you can define the shape. So, before the loop:
steps = PI:PI+deltaq; %steps of the for loop
nsteps = numel(steps); %number of steps
V = zeros(nsteps, 1); %preallocate V rather than growing it in the loop
Dvdq = zeros(nsteps, 1); %same
F = zeros(nsteps, 1);
dFdq = zeros(nsteps, 1);
dPdq = zeros(nsteps, 1); %and preallocate output as a COLUMN vector.
for q = steps %your loop
%... rest of the code unchanged
end
Also note that using global variables is a bad idea. See Parameterizing Functions for better methods.

4 Kommentare

Rafael Marcelino
Rafael Marcelino am 21 Okt. 2019
Thank you for the support, I'll try and correct this points.
Prelocation seems to be a great solution. I'll parametrize it properly to eliminate the global variables.
Thanks for the heads up
darova
darova am 21 Okt. 2019
Is it ok that function name and output name are the same?
function dPdq = dPdq (t, y)
Rafael Marcelino
Rafael Marcelino am 21 Okt. 2019
it didn't return any errors to me...
Guillaume
Guillaume am 22 Okt. 2019
Oh, I didn't spot that. Even if it doesn't result in an error, it's not something you should do. I would strongly recommend you change the variable name or the function name.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Programming finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 21 Okt. 2019

Kommentiert:

am 22 Okt. 2019

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by