Modifying function to get only one value

조회 수: 1 (최근 30일)
Akhil
Akhil 2024년 4월 2일
답변: Manikanta Aditya 2024년 4월 8일
How to modify the following function such that output values (x,y,w) come out either for:
abs((w(r2) - ((x(r1)-a(i))^2 + (y(r1)-b(i))^2)) > (w(r1) * ((x(r2)-a(i))^2 + (y(r2)-b(i))))^2)
or
abs((w(r2) - ((x(r1)-a(i))^2 + (y(r1)-b(i))^2)) < (w(r1) * ((x(r2)-a(i))^2 + (y(r2)-b(i))))^2),
the original code is mentioned below
function f = objective(vars, a, b, reg1, reg2)
x = vars(1:26);
y = vars(27:52);
w = vars(53:end);
f = 0;
for i = 1:numel(a)
r1 = reg1(i);
r2 = reg2(i);
f = f + max(0,(abs((w(r2) - ((x(r1)-a(i))^2 + (y(r1)-b(i))^2)) - (w(r1) * ((x(r2)-a(i))^2 + (y(r2)-b(i))))^2)));
end
  댓글 수: 1
Torsten
Torsten 2024년 4월 2일
편집: Torsten 2024년 4월 2일
I don't understand your question. But an answer that is surely suitable in your case is: use an if-statement.

댓글을 달려면 로그인하십시오.

답변 (1개)

Manikanta Aditya
Manikanta Aditya 2024년 4월 8일
Hello,
To modify the function so that it outputs values (x), (y), and (w) based on the conditions you've specified, you can incorporate an if statement as suggested by @Torsten.
The conditions you've mentioned seem to be criteria for selecting or processing specific cases rather than directly affecting the output format.
However, it's not entirely clear how you want to use these conditions to modify the output directly since the original function accumulates a scalar value 'f' based on all iterations.
function f = objective(vars, a, b, reg1, reg2)
x = vars(1:26);
y = vars(27:52);
w = vars(53:end);
f = 0;
for i = 1:numel(a)
r1 = reg1(i);
r2 = reg2(i);
condition1 = abs((w(r2) - ((x(r1)-a(i))^2 + (y(r1)-b(i))^2)) > (w(r1) * ((x(r2)-a(i))^2 + (y(r2)-b(i))^2))^2);
condition2 = abs((w(r2) - ((x(r1)-a(i))^2 + (y(r1)-b(i))^2)) < (w(r1) * ((x(r2)-a(i))^2 + (y(r2)-b(i))^2))^2);
if condition1 || condition2
% Modify this part as needed based on how you want to use the conditions
f = f + max(0, (abs((w(r2) - ((x(r1)-a(i))^2 + (y(r1)-b(i))^2)) - (w(r1) * ((x(r2)-a(i))^2 + (y(r2)-b(i))^2))^2)));
else
% Optionally, handle cases where neither condition is met
% For example, you could simply skip these cases or handle them differently
end
end
end
This modification checks each of the conditions you've specified (condition 1 and condition 2) and only performs the calculation and accumulation off 'f' if either of the conditions is true.
Hope this helps, Thank you.

카테고리

Help CenterFile Exchange에서 Mathematics에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by