MATLAB: Unable to perform assignment because the size of the left side is 4-by-1 and the size of the right side is 5-by-1. How to work around this

for loopmatricesmismatch size

Hello, I'm running into an issue with my code where the left and the right side matrices' sizes do not match on the 2nd iteration of the for loop. Essentially, what happens is, in the first iteration, solving for the roots of p_bar would return 4 complex roots for p_bar_n. Extracting those 4 to omega_qus would give it a 4×1 size. In the 2nd iteration, p_bar_n returns with 5 complex roots. Therefore, it gives me this error. If I try to pre-allocate for omega_qus such as omega_qus = zeros(5), the first iteration would not work. Can somebody help me find a way to work around this?
%Quasi-unsteady aerodynamics (unsteady aero w/ no aerodynamic mass):
clear flutter_det p_bar_n A_11 A_12 A_21 A_22 ind
syms p_bar
for r=1:length(U_bar)
C = (0.55*p_bar + 0.15*U_bar(r))/(p_bar + 0.15*U_bar(r));
A_11 = mu*p_bar^2 + 2*U_bar(r)*C*p_bar + mu*(omegah_omegaa)^2;
A_12 = mu*x_alpha*p_bar^2 + (1 + 2*(1/2 - a)*C)*U_bar(r)*p_bar + ...
2*C*U_bar(r)^2;
A_21 = mu*x_alpha*p_bar^2 - 2*(1/2 + a)*U_bar(r)*C*p_bar;
A_22 = mu*r_alpha_sq*p_bar^2 + ...
((1/2 - a) - 2*(1/4 - a^2)*C)*U_bar(r)*p_bar + ...
(mu*r_alpha_sq - 2*(1/2 + a)*C*U_bar(r)^2);
flutter_det = det([A_11, A_12; A_21, A_22]);
flutter_det = simplify(flutter_det);
p_bar_n = eval(vpasolve(flutter_det));
[omega_qus(:,r), ind] = sort(imag(p_bar_n));
sigma_qus(:,r) = real(p_bar_n(ind));
end

Best Answer

Do not assign the results of sort() directly into omega_qus(:,r) . Instead, assign it to a temporary variable. Compare the size of the temporary variable to the existing number of rows of omega_qus. If the size of the temporary variable is no larger than the existing omega_qus rows, then assign
LT = length(Temp);
omega_qus(1:LT, r) = Temp;
omega_qus(LT+1:end, r) = FILLER;
where FILLER is a value you have chosen to signal that the slot is not used. For example you might use NaN.
If the size of the temporary variable is longer than the eixsting omega_qus rows, then assign
LT = length(Temp);
omega_qus(end+1:LT, 1:r-1) = FILLER;
omega_qus(:,r) = Temp;
where FILLER is the same as above, a value you have chosen to signal that a slot is not used.
In the special case that the FILLER value is 0, then the code can be abbreviated.
The alternative to using a FILLER is to make omega_qus a cell array.
Related Question