Trying to graph a function I made but it seems to only take the first x value.

9 vues (au cours des 30 derniers jours)
For one of my classes i was tasked with making a function that will solve for the area under a function, specifically the frensel function. I have created the function and it seems to work well, but when it comes to the second half of the assignment which happens to be graphing the change in the area from x= 0-3 next to the function sin(0.5*pi*(x)^2) I cant seem to get it to work correctly. I can get it to graph the sin function but when it tries to graph the function I made it only uses 0.
(Sorry if the format or anything looks weird this is my first time using any help forums)
Not looking for anyone to solve my problem 100% for me, Just hoping someone can point me in the right direction or tell me what I am doing wrong.

Réponse acceptée

Stephen23
Stephen23 le 29 Nov 2024
Modifié(e) : Stephen23 le 29 Nov 2024
Explanation
The basic problem is that you wrote your function assuming only a scalar input:
Fresnel(2)
ans = 0.3434
However you did not write the function to accept a non-scalar input:
Fresnel(1:5)
Warning: Colon operands must be real scalars. This warning will become an error in a future release.
ans = 0.4388
The COLON operator simply uses the first element of any non-scalar input and disregards the rest. The warning is a prompt for you to investigate what your code is doing.
Solutions
You could do one of these:
  1. Vectorize the function: https://www.mathworks.com/help/matlab/matlab_prog/vectorization.html
  2. Use a loop/ARRAYFUN within the function so that it works over multiple input values.
  3. Call the function multiple times on scalar values, e.g. using a loop or ARRAYFUN:
x = 0:0.01:3;
y = arrayfun(@Fresnel,x);
y2=sin(0.5*pi.*(x).^2);
plot(x,y,'bx',x,y2)
  3 commentaires
Stephen23
Stephen23 le 29 Nov 2024
@Lucas: if my answer helped you please remember to click the accept button.
Lucas
Lucas le 29 Nov 2024
Should be accepted now sorry

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by