MATLAB: “Unable to perform assignment because the indices on the left side are not compatible with the size of the right side.”

function scriptvectors

I am trying to use the following function but the error keeps occurring in Line 14:
function r = rxnrate(V,F)
global k Keq f P
Fa=F(1);
Fb=F(2);
Fc=F(3);
Fd=F(4);
Pa=(Fa./f)*P;
Pb=(Fb./f)*P;
Pc=(Fc./f)*P;
Pd=(Fd./f)*P;
Fa=Fb;
Fc=Fd;
f=Fa+Fb+Fc+Fd;
r(1)=-k.*((Pa.*Pb)-(Pc.*Pd./Keq));
r(2)=-k.*((Pa.*Pb)-(Pc.*Pd./Keq));
r(3)=k.*((Pa.*Pb)-(Pc.*Pd./Keq));
r(4)=k.*((Pa.*Pb)-(Pc.*Pd./Keq));
r=r';
end
I am also trying to use this function for the following script:
%This script will plot the respective flowrate versus the volume of
%the reactor for the following reaction:
%CO + H2O <--> CO2 + H2 where CO = A, H2O = B, CO2 = C, H2 = D
clear all;
clc;
P=1; %System pressure in atm
R=8.314*10^-3; %Ideal gas constant in kJ/mol*K
k0=6.195*10^8; %Reference rate constant in mol/(atm^2*m^3*min)
f=33; %Inlet molar flowrate in kmol/min
Fao=(0.5*f); Fbo=(0.5*f); Fco=0; Fdo=0; %Inlet flow rates for all species
T1=450; %System temperature in K


T2=550; %System temperature in K
T3=650; %System temperature in K
k=k0*exp(-47.53/(R*T1)); %Rate constant with respect to temperature
Keq=exp((4577.8/T1)-4.33); %Equilibrium constant with respect to temperature
V=[0 0.25];
Fo=[Fao Fbo Fco Fdo];
[V,F]=ode45(@rxnrate,V,Fo);
plot(V,F);
Thank you for the help!

Best Answer

Please do not ever use global variables.
This works:
function r = rxnrate(V,F, k, Keq, f, P)
Fa=F(1);
Fb=F(2);
Fc=F(3);
Fd=F(4);
Pa=(Fa./f)*P;
Pb=(Fb./f)*P;
Pc=(Fc./f)*P;
Pd=(Fd./f)*P;
Fa=Fb;
Fc=Fd;
f=Fa+Fb+Fc+Fd;
r(1)=-k.*((Pa.*Pb)-(Pc.*Pd./Keq));
r(2)=-k.*((Pa.*Pb)-(Pc.*Pd./Keq));
r(3)=k.*((Pa.*Pb)-(Pc.*Pd./Keq));
r(4)=k.*((Pa.*Pb)-(Pc.*Pd./Keq));
r=r';
end
P=1; %System pressure in atm
R=8.314E-3; %Ideal gas constant in kJ/mol*K
k0=6.195E8; %Reference rate constant in mol/(atm^2*m^3*min)
f=33; %Inlet molar flowrate in kmol/min
Fao=(0.5*f); Fbo=(0.5*f); Fco=0; Fdo=0; %Inlet flow rates for all species
T1=450; %System temperature in K


T2=550; %System temperature in K
T3=650; %System temperature in K
k=k0*exp(-47.53/(R*T1)); %Rate constant with respect to temperature
Keq=exp((4577.8/T1)-4.33); %Equilibrium constant with respect to temperature
V=[0 0.25];
Fo=[Fao Fbo Fco Fdo];
[V,F]=ode45(@(V,F)rxnrate(V,F, k, Keq, f, P),V,Fo);
plot(V,F);
The problem is that you did not declare the variables to be global in both your calling script and ‘rxnrate’. However, since you will never again use global variables, and will always pass necessary variables as additional parameters to your functions instead, there is no need to mention that further.