- Mark up your code so that it looks like code. That helps us distinguish code from comments.
- Report ALL of the red error message that MATLAB returns
- Give us working code so we can reproduce your issue. This means give us the inputs you used for your function that cause it to throw an error
I am getting this error "The right and left hand sides must have the same number of elements" while computing g(i)
32 次查看(过去 30 天)
显示 更早的评论
function [Sa,Sb,Sc]= control(xhatout,Vo_meas,v_ref,If_k)
% Sampling time of the predictive algorithm [s]
Ts = 33e-6;
%f = 50*(2*pi); % frequency [rad/s]
Vdc = 700; % DC-link voltage [V]
L = 2e-3;
C = 50e-6;
% Voltage vectors
v0 = 0;
v1 = 2/3*Vdc;
v2 = 1/3*Vdc + 1j*sqrt(3)/3*Vdc;
v3 = -1/3*Vdc + 1j*sqrt(3)/3*Vdc;
v4 = -2/3*Vdc;
v5 = -1/3*Vdc - 1j*sqrt(3)/3*Vdc;
v6 = 1/3*Vdc - 1j*sqrt(3)/3*Vdc;
v7 = 0;
v = [v0 v1 v2 v3 v4 v5 v6 v7];
% Switching states
states = [0 0 0;1 0 0;1 1 0;0 1 0;0 1 1;0 0 1;1 0 1;1 1 1];
% Previous Optimum vector and measured current at instant k-1
persistent x_old i_old v_old
% Initialize values
if isempty(x_old), x_old = 1; end
if isempty(i_old), i_old = 0+1j*0; end
if isempty(v_old), v_old = 0+1j*0;end
g = zeros(2,8);
% Read current reference inputs at sampling instant k
vk_ref = v_ref(1) + 1j*v_ref(2);
vk = Vo_meas(1) + 1j*Vo_meas(2);
io = [0 0 1]*xhatout;
for i = 1:8
% Cost function
vi = Vdc*x_old;
if_k1 = If_k+((Ts/L)*(vi-Vo_meas));
vc_k1 = vk+((Ts/C)*(If_k-io));
g(i) = abs(real(v_ref - vc_k1)) + abs(imag(v_ref - vc_k1));
end
% Optimization
[~,x_opt] = min(g);
% Store the present value of x_opt
x_old = x_opt;
% Output switching states
Sa = states(x_opt,1);
Sb = states(x_opt,2);
Sc = states(x_opt,3);
1 个评论
Alan Weiss
2022-1-21
Please help us understand what you are doing by the following:
Alan Weiss
MATLAB mathematical toolbox documentation
回答(2 个)
Voss
2022-1-21
Try replacing this line:
g(i) = abs(real(v_ref - vc_k1)) + abs(imag(v_ref - vc_k1));
with this line:
g(:,i) = abs(real(v_ref(:) - vc_k1(:))) + abs(imag(v_ref(:) - vc_k1(:)));
The reason is that g(i) is a single element of g, but v_ref has (at least) 2 elements (don't know how many because we don't know what you send to the function), so the right-hand side is going to be non-scalar. From the initialization of g (g = zeros(2,8);) we can see the size of g is 2-by-8 so it's likely that each iteration of the loop is meant to set a column of g, i.e., g(:,i), rather than a single element g(i).
0 个评论
Cheng Syuan Ye
2022-2-9
Hello, have you solved the problem, I am also researching recently, what is the final solution?
1 个评论
Voss
2022-2-9
The answer to this particular question is:
https://www.mathworks.com/matlabcentral/answers/1632345-i-am-getting-this-error-the-right-and-left-hand-sides-must-have-the-same-number-of-elements-while#answer_879170
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!