Why does this code give error?

39 次查看(过去 30 天)
When I run the main, it gives me the following error:
Unable to perform assignment because the indices on the left side are not compatible with
the size of the right side.
Error in main (line 55)
two(run_idx,:) = temp(run_idx,ix1);
>>

采纳的回答

Torsten
Torsten 2024-7-25
编辑:Torsten 2024-7-25
Force the array ix1 to be of the same length as ix by explicitly allocating it with the size of ix:
% Run the GBO algorithm multiple times
for run_idx = 1:num_runs
% Run the GBO Algorithm
[Best_fitness, BestPositions, time1] = GBO(nP, MaxIt, lb, ub, dim, @(b) myfun(b, u, P_far, P_near));
% Store output of GBO in desired variables
one(run_idx) = Best_fitness; % Fitness value
temp(run_idx, :) = BestPositions; % Best estimated vector
time(run_idx) = time1; % Elapsed time
% Perform swapping
[~, ix] = sort(u); % u is my desired vector
ix1 = zeros(size(ix));
[~, ix1(ix)] = sort(1:length(temp(run_idx,:)));
two(run_idx,:) = temp(run_idx,ix1)
end
  9 个评论
Torsten
Torsten 2024-7-26
编辑:Torsten 2024-7-26
The arrangement of "u" and "two" now is the same - meaning that if u has its i-th biggest element at position j, "two" will also have its i-th biggest element at position j. So the ordering of the two arrays is consistent.
I don't know why you get a different arrangement of BestPositions and u - in my opinion, this shouldn't be the case so that no post-ordering should be necessary (e.g. if you use an objective function like sum(BestPositions-u).^2).
Sadiq Akbar
Sadiq Akbar 2024-7-26
Thanks a lot for your kind help. Yes, you are right. Actually I was comparing "best_positions" with "u" which was not same as u. Then I replaced the 56th line which was as:
best_positions = temp(best_idx, :);
by the following
best_positions = two(best_idx, :);
and re-ran it. Then the results were the same. Thanks a lot.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Quadratic Programming and Cone Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by