Clear Filters
Clear Filters

Why does this code give error?

43 views (last 30 days)
Sadiq Akbar
Sadiq Akbar on 25 Jul 2024 at 12:42
Commented: Sadiq Akbar on 26 Jul 2024 at 10:43
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);
>>

Accepted Answer

Torsten
Torsten on 25 Jul 2024 at 13:01
Edited: Torsten on 25 Jul 2024 at 13:02
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 Comments
Torsten
Torsten on 26 Jul 2024 at 9:36
Edited: Torsten on 26 Jul 2024 at 9:37
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 on 26 Jul 2024 at 10:43
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.

Sign in to comment.

More Answers (0)

Categories

Find more on Quadratic Programming and Cone Programming in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!