Why does this code give error?

2 ビュー (過去 30 日間)
Sadiq Akbar
Sadiq Akbar 2024 年 7 月 25 日
コメント済み: Sadiq Akbar 2024 年 7 月 26 日
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 Center および File ExchangeCalculus についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by