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 CenterFile Exchange에서 Calculus에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by