How to input multiple values to the same variable to avoid having to keep changing the values and rerunning the program each time?

27 views (last 30 days)
Hello, I am trying to write a program that will output three different values based on three different input combinations, e.g. n1 = f(sigma_x1,sigma_y1,sigma_z1), n2 = f(sigma_x2,sigma_y2,sigma_z2), and n3 = f(sigma_x3,sigma_y3,sigma_z3).
Here is my attempt at doing that. How can I do this calculation without getting an error in the program? Thank you.
sigma_x = [100 200 300];
sigma_y = [400 500 600];
tau_xy = [700 800 900];
%--------------------------------------%
S_y = 350; % MPa (Given)
sigma_max_min_a = ((sigma_x+sigma_y)/2)+sqrt(((sigma_x - sigma_y)/2).^2+tau_xy.^2);
sigma_max_min_b = ((sigma_x+sigma_y)/2)-sqrt(((sigma_x - sigma_y)/2).^2+tau_xy.^2);
if sigma_max_min_a > 0 && sigma_max_min_b > 0
if sigma_max_min_a > sigma_max_min_b
sigma_max = sigma_max_min_a;
sigma_min = 0;
else
sigma_max = sigma_max_min_b;
sigma_min = 0;
end
elseif sigma_max_min_a < 0 && sigma_max_min_b < 0
if sigma_max_min_a < sigma_max_min_b
sigma_max = 0;
sigma_min = sigma_max_min_a;
else
sigma_max = 0;
sigma_min = sigma_max_min_b;
end
elseif sigma_max_min_a > 0 && sigma_max_min_b < 0
sigma_max = sigma_max_min_a;
sigma_min = sigma_max_min_b;
else
sigma_max = sigma_max_min_b;
sigma_min = sigma_max_min_a;
end
Operands to the logical AND (&&) and OR (||) operators must be convertible to logical scalar values. Use the ANY or ALL functions to reduce operands to logical scalar values.
n = S_y/(sigma_max - sigma_min)

Answers (1)

Jan
Jan on 10 Dec 2022
Edited: Jan on 10 Dec 2022
Do you get a message concering the && operators? They need scalars are inputs. If you provide vectors, use & .
But then
if sigma_max_min_a > 0 && sigma_max_min_b > 0
has a vectors as condition. Because conditions of if commands must be scalars, Matlab inserts an all() implicitly. If you want to calculate the code for the 1st elements of sigma_x/y/z, then for the 2nd elements, usw. your code need more modifications.
The simple solution would be a loop.
sigma_x = [100 200 300];
sigma_y = [400 500 600];
tau_xy = [700 800 900];
result = zeros(1, 3);
for k = 1:3
result(k) = f(sigma_x(k), sigma_y(k), tau_xy(k));
end
Vectorizing the code is useful, if you applie it for millions of values and speed matters. Then logical indexing is the way to go.
By the way, avoid name monsters like "sigma_max_min_a" and "sigma_max_min_". The code is small and the readability is higher, if you simply call them "a" and "b".

Categories

Find more on Functions in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!