Using 'if' to conduct specific matrix cell operations

1 view (last 30 days)
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

Accepted Answer

Matt J
Matt J on 19 Nov 2021
P2=ones(size(P));
subset=(P<1);
P2(subset)=1-Pfailgrid(subset);
  7 Comments
Matt J
Matt J on 19 Nov 2021
Edited: Matt J on 19 Nov 2021
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 on 19 Nov 2021
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!

Sign in to comment.

More Answers (0)

Products


Release

R2021b

Community Treasure Hunt

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

Start Hunting!