How do I create an element wise if-else code, and apply equations to inputs that meet certain criteria?
9 次查看(过去 30 天)
显示 更早的评论
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!
0 个评论
回答(1 个)
Jan
2022-3-29
编辑:Jan
2022-3-29
"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 个评论
Jan
2022-3-30
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.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Graphics Object Programming 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!