Why does this code give error?

4 visualizzazioni (ultimi 30 giorni)
Sadiq Akbar il 25 Lug 2024
Commentato: Sadiq Akbar il 26 Lug 2024
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);
>>
0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Risposta accettata

Torsten il 25 Lug 2024
Modificato: Torsten il 25 Lug 2024
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 CommentiMostra 7 commenti meno recentiNascondi 7 commenti meno recenti
Torsten il 26 Lug 2024
Modificato: Torsten il 26 Lug 2024
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 il 26 Lug 2024
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.

Accedi per commentare.

Categorie

Scopri di più su Calculus in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by