How do I create an element wise if-else code, and apply equations to inputs that meet certain criteria?

10 vues (au cours des 30 derniers jours)
Here is my code, (sigma is a (74724,1) column vector)
Eya = 2.83*10^7;
Y = log10((28300.*sigma)/Eya)
X1 = (17.0181 - 19.8713*Y + 4.21366*Y.^2)./(1 - 0.1720606*Y - 0.633592*Y.^2)
X2 = 1./(-.331096 + (4.3261*log(Y))./Y.^2)
if 10.^Y >= 14.4; %**this is where i assume my issue lies**
X = X1;
else
X = X2;
end
N = 10.^X %Allowable number of cycles (should be very high)
nc = 45000; %Total number of actual cycles (constant)
D = nc./N %Damage ratio (should be very low for most values of sigma, and never exceeding 1)
I need a new vector, X, (74724,1) to be created from either X1 or X2 depending on Y meeting the criteria as seen in the if then statement
Any help is much appreciated, Thank you!

Réponses (1)

Jan
Jan le 29 Mar 2022
Modifié(e) : Jan le 29 Mar 2022
"Elementwise" does either mean a loop:
for k = 1:numel(sigma)
Y = log10(28300 * sigma(k) / Eya);
...
end
Or you use logical indexing:
...
m = 10.^Y >= 14.4;
X = zeros(size(sigma));
X(m) = X1(m);
X(~m) = X2(~m);
...
or slightly easier:
...
m = 10.^Y >= 14.4;
X = X2;
X(m) = X1(m);
...
As usual I mention, that 2.83*10^7 is a multiplication and an expensive power operation, while 2.83e7 is a cheap constant.
  2 commentaires
Nick Lavanture
Nick Lavanture le 29 Mar 2022
Thank you, unfortunately none of these solutions worked, here is my current script
clc,clear
Stress = readmatrix('Nonlinear 1 Stress 500psi.txt');
sigma = Stress(:,5);
n = 1;
for n = 1:74723; %this loop converts any sub 1000psi value of sigma to 1000psi, necessay to avoid a negative log and imaginary numbers for X2
if sigma(n) < 1000;
sigma(n) = 1000;
end
n = n+1;
end
%sigma = 13000;
%test input, will overwrite the above data, and output the correct values I am looking for
Eya = 2.83e7;
Y = log10((28300.*sigma)/Eya)
X1 = (17.0181 - 19.8713*Y + 4.21366*Y.^2)./(1 - 0.1720606*Y - 0.633592*Y.^2)
X2 = 1./(-.331096 + (4.3261*log(Y))./Y.^2)
%if 10.^Y >= 14.4;
%X = X1;
%else
%X = X2;
%end
%m = 10.^Y >= 14.4;
%X = X2;
%X(m) = X1(m);
m = 10.^Y >= 14.4;
X = zeros(size(sigma));
X(m) = X1(m);
X(~m) = X2(~m);
N = 10.^X
nc = 45000;
D = nc./N
Jan
Jan le 30 Mar 2022
This is not the way for loops work:
for n = 1:74723 % No ;
if sigma(n) < 1000;
sigma(n) = 1000;
end
n = n+1; % Nope, omit this!
end
A nicer code to perform this without a loop:
sigma = min(sigma, 1000);
Please mention, what "none of these solutions work" mean. Do you get an error message? Does the result differ from your expectations? I do not have your input data, so I cannot run the code by my self. If you do not explain, what the problem is, I cannot guess it.

Connectez-vous pour commenter.

Catégories

En savoir plus sur Graphics Object Programming dans Help Center et File Exchange

Produits


Version

R2022a

Community Treasure Hunt

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

Start Hunting!

Translated by