How to test multiple values in my for and if statement.

7 vues (au cours des 30 derniers jours)
Nathan Downes
Nathan Downes le 1 Mar 2023
Modifié(e) : Jan le 2 Mar 2023
I am trying to run this for discontinutiy functions and I want to know how to test all values for delfection of a beam from 1-35 instead of having to individually type in each number.
for x = 5
if x < 7
x = (.349*x^3 - 237.71*x + 237.36)/(10400000*.0013021);
elseif x >= 7 && x < 23
x = (.349*x^3 -.2833*(x-7)^3 - 237.71*x + 237.36)/((10400000*.0013021));
elseif x >= 23 && x < 34
x = (.349*x^3 -.2833*(x-7)^3 - .3833*(x-23)^3 - 237.71*x + 237.36)/((10400000*.0013021));
else x = 0;
end
end

Réponses (2)

Cameron
Cameron le 1 Mar 2023
Modifié(e) : Cameron le 1 Mar 2023
I'm not sure why you were using x to loop through your variable, but this is how I'd do it.
x = (1:35)';
coeff = zeros(length(x),2);
coeff(x >= 7) = -0.2833;
coeff(x >= 23 & x < 34,2) = -0.3833;
y = (.349*x.^3 + coeff(:,1).*(x-7).^3 + coeff(:,2).*(x-23).^3 - 237.71*x + 237.36)./(10400000*.0013021);
y(x>=34) = 0;
plot(x,y,'-ok')

Jan
Jan le 1 Mar 2023
Modifié(e) : Jan le 2 Mar 2023
x = 1:35;
y = zeros(size(x));
c = 10400000 * 0.0013021; % Leaner code
for k = 1:numel(x)
if x(k) < 7
y(k) = (0.349*x(k)^3 - 237.71*x(k) + 237.36) / c;
elseif x(k) < 23 % x(k) >= 7 was tested before already
y(k) = (0.349*x(k)^3 - 237.71*x(k) + 237.36 - 0.2833*(x(k)-7)^3) / c;
elseif x(k) < 34 % x(k) >= 23 was tested before already
y(k) = (0.349*x(k)^3 - 237.71*x(k) + 237.36 - 0.2833*(x(k)-7)^3 - ...
0.3833*(x(k)-23)^3) / c;
% else, y(k) = 0 is the default value already
end
end
[EDITED] Alternatively:
x = 1:35;
y = zeros(size(x));
q = x < 34;
y(q) = 0.349 * x(q).^3 - 237.71 * x(q) + 237.36;
p = q & x >= 7;
y(p) = y(p) - 0.2833 * (x(p) - 7).^3;
p = q & x >= 23;
y(p) = y(p) - 0.3833 * (x(p) - 23).^3;
y = y / (10400000 * 0.0013021);
Or shorter:
x = 1:35;
y = (0.349 * x.^3 - 237.71 * x + 237.36 ...
- 0.2833 * (max(0, x - 7)).^3 ...
- 0.3833 * (max(0, x - 23)).^3) .* (x < 34) ...
/ (10400000 * 0.0013021);

Catégories

En savoir plus sur NaNs dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by