How to put linspace data into if statement

6 visualizzazioni (ultimi 30 giorni)
Max il 8 Feb 2024
Modificato: Pratyush Swain il 8 Feb 2024
I have a function that relates "theta" (an angle) to "p" (pressure) and I want to graph the two. The parent code initializes the theta array and calls the "pressure" function that relates the two variables:
%% thetavsp
theta = linspace(0,2*pi,50);
p = pressure(theta);
figure;
plot(theta, p);
Inside the pressure function I need to run different code if the theta is between 0 and pi or pi and 2pi. So inside I have an if statement:
if(0 <= theta && theta <= pi)
phase = 1; %compression
elseif(pi < theta && theta <=2*pi)
phase = 2; %expansion
else
disp("Not valid theta");
end
When doing this I get the error: "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."
If I swap the && for & then it tells me the theta is not within the bounds and I get the "Not valid theta" output.
How can I fix this?
2 CommentiMostra NessunoNascondi Nessuno
Stephen23 il 8 Feb 2024
"How can I fix this?"
Forget about IFs, which will not work anyway (unless you write even more complex code).
Learn to operate on arrays using logical indexing, which is the simple MATLAB approach.
Mathieu NOE il 8 Feb 2024
your code can only work if theta is a scalar but not an array , simply because you can do if conditionnal statement only if what follows your if is a logical of length 1 not 50
so your code doesn't work here because those logical are arrays of length 50 :
(0 <= theta & theta <= pi)
(pi < theta & theta <=2*pi)

Accedi per commentare.

Risposta accettata

Vaibhav il 8 Feb 2024
Modificato: Vaibhav il 8 Feb 2024
Hi Max
The issue you are facing is due to MATLAB's distinction between element-wise logical operations and short-circuit logical operations. The operators && and || are meant for short-circuiting operations on scalar logical expressions, while & and | are meant for element-wise operations on arrays.
In your case, "theta" is an array, not a scalar, so you should use element-wise operations. However, you can't simply compare an entire array with a scalar using "if" because "if" expects a single logical value, not an array of logical values.
To fix this, you will need to use a loop to iterate over each element of "theta" or use logical indexing. Here's how you can modify the "pressure" function to handle arrays properly:
function p = pressure(theta)
p = zeros(size(theta)); % Initialize pressure array with the same size as theta
for i = 1:length(theta)
if (0 <= theta(i) && theta(i) <= pi)
phase = 1; %compression
% Calculate pressure for the compression phase
% p(i) = ... (your compression phase calculation here)
elseif (pi < theta(i) && theta(i) <= 2*pi)
phase = 2; %expansion
% Calculate pressure for the expansion phase
% p(i) = ... (your expansion phase calculation here)
else
disp("Not valid theta");
% Handle the invalid theta case, if necessary
end
end
end
Alternatively, if you want to vectorize your code and avoid loops, you can use logical indexing like this:
function p = pressure(theta)
p = zeros(size(theta)); % Initialize pressure array with the same size as theta
% Logical indices for compression phase
compression_idx = (0 <= theta) & (theta <= pi);
% Calculate pressure for the compression phase
p(compression_idx) = ...; % (your vectorized compression phase calculation here)
% Logical indices for expansion phase
expansion_idx = (pi < theta) & (theta <= 2*pi);
% Calculate pressure for the expansion phase
p(expansion_idx) = ...; % (your vectorized expansion phase calculation here)
end
This approach is generally more efficient than using loops, especially for large arrays.
Hope this helps!
0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Più risposte (3)

Mathieu NOE il 8 Feb 2024
Suggestion :
theta = linspace(0,2*pi,50);
p = pressure(theta);
figure;
plot(theta, p);
ylim([0 3])
function phase = pressure(theta)
log1 = (0 <= theta & theta <= pi);
phase1 = 1; %compression
log2 = (pi < theta & theta <=2*pi);
phase2 = 2; %expansion
% combine both outputs depending of their respective validity (log1 ,
% log2)
phase = phase1.*log1 + phase2.*log2;
end
0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Pratyush Swain il 8 Feb 2024
Modificato: Pratyush Swain il 8 Feb 2024
Hi Max,
The error you're encountering is because the "&&" operator in MATLAB is used for scalar logical operations, and you're attempting to use it with an array "theta" (as "linspace" function generates linearly spaced vectors).
Also, like you mentioned,simply replacing "&&" with "&" does not solve the problem.This is because your "if statement" is still expecting a single logical value, not an array of logical values. Since "theta" is an array, you need to apply the condition to each element of "theta".
There are two workarounds in this scenario:
1- Pass values of "theta" array through a loop.
This ensures your "pressure" function only takes in single "theta" value input rather than an array of "theta" values and you dont have to make any changes in the pressure function.
% Define the theta array
theta = linspace(0, 2*pi, 50);
% Initialize an array to hold the pressure values
p = zeros(size(theta));
% Loop over each theta value and calculate the pressure
for i = 1:length(theta)
p(i) = pressure(theta(i));
end
% Plot the results
figure;
plot(theta, p);
ylabel('Pressure');
title('Pressure vs. Theta');
2- Use vectorization or loop in the pressure function
Another workaround is you can make changes in pressure function and use a loop to iterate through the array of "theta" values and apply the conditions to each element, or you can vectorize the operation.
function p = pressure(theta)
% Initialize the pressure array
p = zeros(size(theta));
% Find indices where theta is in the compression phase
indexes_for_compression = theta >= 0 & theta <= pi;
% Find indices where theta is in the expansion phase
indexes_for_expansion = theta > pi & theta <= 2*pi;
% Calculate pressure for compression phase
p(indexes_for_compression) = ... % Your implementation
% Calculate pressure for expansion phase
p(indexes_for_expansion) = ... % Your implementation
% Handle any theta values that are not within the bounds
if any(~(indexes_for_compression | indexes_for_expansion))
disp("Not valid theta");
% Do further implementation if necessary
end
end
0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Voss il 8 Feb 2024
phase = NaN(size(theta));
idx = (0 <= theta) && (theta <= pi); % compression
phase(idx) = 1;
idx = (pi < theta) && (theta <= 2*pi) % expansion
phase(idx) = 2;
if any(isnan(phase))
disp('Some invalid theta')
end
0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

Categorie

Scopri di più su Programming in Help Center e File Exchange

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by