Using 'if' to conduct specific matrix cell operations

조회 수: 1 (최근 30일)
Daniel McDonald
Daniel McDonald 2021년 11월 19일
댓글: Daniel McDonald 2021년 11월 19일
I'm trying to use the 'if' function on specific matrix cells to create a new matrix then find the product of that matrix, which will ultimately be used to minimuze a risk function. So far I have Points 'P' and the associated failure 'Pfailgrid', both 1x200 matrices, but regardless of my changes in P (which are binary), y = 0. Any tips would be appreciated, I'm sure I haven't clarified well enough so please let me know if I can do so. Thank you.
function y = DistObj(P)
Pfailgrid = readmatrix('PfailColumn.xlsx'); %1x200
P = readmatrix('Points.xlsx'); %1x200
if P(:,1) <= 1
P2(:,1) = 1-Pfailgrid(:,1);
else
P2(:,1) = 1;
end
y = prod(P2); % makes 1x200 = Ppass
end

채택된 답변

Matt J
Matt J 2021년 11월 19일
P2=ones(size(P));
subset=(P<1);
P2(subset)=1-Pfailgrid(subset);
  댓글 수: 7
Matt J
Matt J 2021년 11월 19일
편집: Matt J 2021년 11월 19일
No, the output y still doesn't depend on the input P2 at all. You overwrite the input P2 in this line
P2 = ones(size(P));
and the original values of P2 never affect anything.
Daniel McDonald
Daniel McDonald 2021년 11월 19일
Matt, I think this fixed it. I definitely had some fundamental errors about making this function and, in a quest for an answer, forgot what I was trying to solve for! By changing y = DistObj(x) and setting P = x(1) I believe that resolves the issue. The code below is what I plan to use in the optimization:
% Objective function - Solving for P
function y = DistObj(x)
Pfailgrid = readmatrix('PfailColumn.xlsx'); %1x200
P = x(1); %readmatrix('Points.xlsx'); %1x200
P2 = ones(size(P));
subset = (P<1);
P2(subset)=1-Pfailgrid(subset);
y = sum(log(P2)); % makes scalar = Ppass
% y = prod(P2);
end
%Import excel matrices
Dist = readmatrix('Distance.xlsx');
Pfailgrid = readmatrix('Pfail10_20.xlsx');
f = @(x)DistObj(x);
%Call x0
x0 = readmatrix('Points.xlsx');
%upper and lower bounds
lb = readmatrix('lb.xlsx');
ub = readmatrix('ub.xlsx');
nonlcon = @DistNonlCons;
%Run fmincon to find surface points with minimum risk
PointsNew = fmincon(f,x0,[],[],[],[],[],[],[]);
PointsNew;
The second fmincon portion is still a work in progress but hopefully should be smoother! Thanks for your help and please let me know if you've got any additional comments!

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

추가 답변 (0개)

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by