How to change one line of code?

1 view (last 30 days)
Jakub Reczek
Jakub Reczek on 19 Oct 2019
Edited: Stephen23 on 19 Oct 2019
Hi! I have 2 files, one function and a main code. In function code is:
function y = myfun(x)
a(:,2)=10.0*ones(4,1);
for j=1:2;
a(2*j-1,1)=3.0; a(2*j,1)=0.1;
a(2*j-1,3)=30.0; a(2*j,3)=35.0;
end
c(1)=1.0;c(2)=1.2;c(3)=3.0;c(4)=3.2;
p(1,1)=0.36890;p(1,2)=0.11700;p(1,3)=0.26730;
p(2,1)=0.46990;p(2,2)=0.43870;p(2,3)=0.74700;
p(3,1)=0.10910;p(3,2)=0.87320;p(3,3)=0.55470;
p(4,1)=0.03815;p(4,2)=0.57430;p(4,3)=0.88280;
s = 0;
for i=1:4;
sm=0;
for j=1:3;
sm=sm+a(i,j)*(x(j)-p(i,j))^2;
end
s=s+c(i)*exp(-sm);
end
y = -s;
In a main code i have a call this function
Particle_Cost=zeros(PopulationSize,1);
for i=1:PopulationSize
Particle_Cost(i,:) = myfun(Particle_Position(i,:));
end
I wanted to change this function my fun to:
function y = myfun(x)
y = sum(x(1)^2+x(2)^2+x(3)^2);
end
But it dosent work for a main code. Please tell me how to fix it. I will be a grateful.

Accepted Answer

Stephen23
Stephen23 on 19 Oct 2019
Edited: Stephen23 on 19 Oct 2019
function y = myfun(x)
y = sum(x.^2);
end
Or if you really only want to sum the first three elements:
function y = myfun(x)
y = sum(x(1:3).^2);
end

More Answers (0)

Community Treasure Hunt

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

Start Hunting!