These 3 codes when run give error
5 views (last 30 days)
Show older comments
I have 3 codes as given in attachment. When I run the "main.m", it gives the following error:
Index in position 1 exceeds array bounds. Index must not exceed 1.
Error in ArGeo (line 17)
cosd(b(2, :)) .* cosd(b(1, :)); % x-component
Error in main>@(b)ArGeo(b,u,Noise)+penaltyTerm(b,u) (line 25)
[time,gBest,gBestScore]=WHO(20,100,lb,ub,dim,@(b) ArGeo(b,u,Noise)+penaltyTerm(b, u));
Error in WHO (line 47)
group(i).cost=fobj(group(i).pos);
Error in main (line 25)
[time,gBest,gBestScore]=WHO(20,100,lb,ub,dim,@(b) ArGeo(b,u,Noise)+penaltyTerm(b, u));
>>
0 Comments
Accepted Answer
Voss
on 1 May 2024
In WHO.m lines 45-48, you have
for i=1:Nfoal
group(i).pos=lb+rand(1,dim).*(ub-lb);
group(i).cost=fobj(group(i).pos);
end
where dim is 2, and lb and ub are each 1xdim vectors. Thus, group(i).pos is created as a 1xdim vector on line 46, and the error happens after fobj (which is @(b) ArGeo(b,u,Noise)+penaltyTerm(b, u)) is called on line 47, because inside ArGeo.m, input b, which is group(i).pos in WHO.m, is expected to have at least 2 rows:
kb = pi * [
cosd(b(2, :)) .* cosd(b(1, :)); % x-component
sind(b(2, :)) .* cosd(b(1, :)); % y-component
sind(b(1, :)) % z-component
];
That's the reason for the error.
As far as how to fix it, I suspect that lines 26-29 of WHO.m are not doing what's intended:
if size(ub,1)==1
ub=ones(1,dim).*ub;
lb=ones(1,dim).*lb;
end
Since ub and lb are each 1xdim vectors, you are multiplying each element of ub and lb by 1, which leaves them unchanged. Instead, I guess you want to replicate them so that they have exactly 2 rows (not dim rows), which could be done like:
if size(ub,1)==1
ub=ones(2,1).*ub;
lb=ones(2,1).*lb;
end
Then they are of size 2xdim, which seems like what's intended.
9 Comments
More Answers (0)
See Also
Categories
Find more on Matrix Indexing 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!