Dimension 2 is fixed on the left-hand side but varies on the right ([1 x 1] ~= [1 x :?])

12 visualizaciones (últimos 30 días)
Hi all,
I am trying to use an Matlab function block to sort array:
function [Y1, Y2,Y3,Y4] = selectionSort( Vc1, Vc2, Vc3, Vc4, iu)
A=[ Vc1, Vc2, Vc3, Vc4];
Y1=0; Y2=0; Y3=0; Y4=0; Y5=0;
if iu >= 0
B = sort(A);
Y1=find(A==B(1),1, 'first')
Y2=find(A==B(2),1, 'first');
Y3=find(A==B(3),1, 'first');
Y4=find(A==B(4),1, 'first');
But get four errors. How can I solve these errors? Thank you for any advice. Here are the errors:
Dimension 2 is fixed on the left-hand side but varies on the right ([1 x 1] ~= [1 x :?]). Function 'MATLAB Function' (#81.264.266), line 9, column 1: "Y1"
  1 comentario
Walter Roberson
Walter Roberson el 21 de Mzo. de 2025
Are you sure about your code?
If for example the inputs were [1 2 2 4] then the output would be Y1 = 1, Y2 = 2, Y3 = 2, Y4 = 4 rather than Y1 = 1, Y2 = 2, Y3 = 3, Y4 = 4.
It is not clear why you do not simply do
[~, Y] = sort(B);
Y1 = Y(1);
Y2 = Y(2);
Y3 = Y(3);
Y4 = Y(4);

Iniciar sesión para comentar.

Respuestas (1)

Rajanya
Rajanya el 21 de Mzo. de 2025
These errors occur because Simulink is unable to determine the output dimensions from the 'find ' function. Since the left-hand side is a 1x1 scalar, it throws an error when it cannot confirm that the right-hand side will also be a 1x1 scalar.
Modifying the function as the following resolved the errors-
A=[ Vc1, Vc2, Vc3, Vc4];
Y1=0; Y2=0; Y3=0; Y4=0;
if iu >= 0
B = sort(A);
p=find(A==B(1),1, 'first'); % store the result in a var and
Y1=p(1); % access its first element
q=find(A==B(2),1, 'first');
Y2=q(1);
r=find(A==B(3),1, 'first');
Y3=r(1);
s=find(A==B(4),1, 'first');
Y4=s(1);
end
Hope this helps!
Thanks.
  1 comentario
Walter Roberson
Walter Roberson el 21 de Mzo. de 2025
When the 'first' option is used for find(), the output will either be of length 1 (if find is successful) or length 0 (if find is not successful).
If, hypothetically, the find were not successful, then indexing the output variable would not be successful.
When you say B = sort(A) and then find matching elements of B, there is the possibility that A contains enough nans such that B(4) and possibly earlier are NaN. In such a case, even though B is extracted from A, A==B(4) would fail since comparing for equality to NaN always fails, including the case NaN == NaN . (sort() always sorts NaN last.) So indexing s(1) in particular could fail, and possibly earlier such as r(1) if there were enough NaN in A.

Iniciar sesión para comentar.

Categorías

Más información sobre Shifting and Sorting Matrices en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by