How to use if statement in function?

4 vues (au cours des 30 derniers jours)
Roko Serdar
Roko Serdar le 9 Avr 2021
Commenté : Roko Serdar le 9 Avr 2021
How do I define that my N needs to be >0. I tried if but I get error like
Output argument "prvi" (and maybe others) not assigned during call to "func1".
here is my writen code
function prvi = func1(x, N)
for k=1:N
prvi=(1-(4*x^2)/(pi^2*(2*k-1)^2))
end
end

Réponse acceptée

James Tursa
James Tursa le 9 Avr 2021
Modifié(e) : James Tursa le 9 Avr 2021
Add this code to the top of your function:
if( N <= 0 )
error('N needs to be > 0')
end
That being said, your loop probably doesn't do what you intended since it only assigns prvi based on the last iteration. Also, there are many other checks you can make on x and N to make sure they are the correct type, size, etc.
  2 commentaires
Cris LaPierre
Cris LaPierre le 9 Avr 2021
You could also look into Function Argument Validation.
Roko Serdar
Roko Serdar le 9 Avr 2021
thank you guys

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Programming 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