Numerical Optimization Code: ERROR Matrix Dimensions Must Agree

I am trying to run a code for numerical optimization and I encountered the error message "matrix dimensions must agree". Both fitx and fitx_new were generated using a for loop. When I checked the size of x (for fitx) and the size of ui (for fitx_new), I found that they are the same. Has anyone encountered this kind of problem before? If so, what should I do? Thanks in advance!

4 commentaires

Stephen23
Stephen23 le 1 Août 2018
Modifié(e) : Stephen23 le 1 Août 2018
"When I checked the size of x (for fitx) and the size of ui (for fitx_new), I found that they are the same"
No you didn't check the size, because you used length.
Do NOT use length ! length is an abomination that should be ignored and not used, because the dimension that its output measures changes depending on the size of the array. Ouch!
Always use size or numel. Please show us the output of these commands:
size(fitx)
size(fitx_new)
Hi, Stephen! Thank you for taking the time to look into this. Here are the output of size(fitx) and size(fitx_new).
The vector fitx corresponds to the function values where the input is just the row vectors of the matrix x. Similarly, the vector fitx_new corresponds to the function values where the input is just the row vectors of the matrix ui. The size of both x and ui is 139x8 (since it's an 8-Dimensional optimization problem).
fitx and fitx_new have different sizes so fitx-fitx_new returns 'Matrix dimensions must agree'. You said you created both in a loop, however you didn't show the code. It is quite challenging to guess why your loop creates 2 vectors of different length without having any information about it.
for i = 1:length(x)
fitx(i) = f(x(i,:));
end
for i = 1:length(ui)
fitx_new(i) = f(ui(i,:));
end
These were the codes I used to generate both fitx and fitx_new. There are lines in between to generate for ui. But in any case when I try to query the size of both x and ui, they agree but the output of the loops don't.

Connectez-vous pour commenter.

Réponses (0)

Question posée :

JDL
le 1 Août 2018

Commenté :

JDL
le 1 Août 2018

Community Treasure Hunt

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

Start Hunting!

Translated by