Hi MATLAB-Folks,
I'm asking with a beginner problem for your help, I searched the forum for an answer but without sucess:
I have a script, that creates a vector, lets say as an example:
>> g_x_contact=[0 0 1 2 3 4 0 0]
afterwards I'm creating a function, that uses the corresponding value of the vector within.
For example:
function Integral = pressure_integral(x)
Integral = g_x_contact(x).*(x/2)
end
So I want the function to use the value at position x and calculate the according steps afterwards.
Here the promt-line >> pressure_integral(6) should calculated with the sixth element: 4.*(6/2)=12
Instead I get the error-Message
Unrecognized function or variable 'g_x_contact'.
Error in pressure_integral (line 6)
Integral = g_x_contact(x).*(x/2)
Can anybody give me a hint, how the access the Vector?
Thank you in advance and very best
Christian

 Akzeptierte Antwort

Bob Thompson
Bob Thompson am 2 Mär. 2021
Bearbeitet: Bob Thompson am 2 Mär. 2021

0 Stimmen

I believe this is the purpose of global variables, but I could be wrong. I don't really use them much.

5 Kommentare

Stephen23
Stephen23 am 2 Mär. 2021
Much better than global variables (which should be avoided):
  • nested functions
  • passing data as input argument (recommended by the MATLAB documentation).
Christian S.
Christian S. am 2 Mär. 2021
Thank you for your answers Bob and Stephen,
I came across the method of passing data as an input. I thought my targeted use for this fuction -to calculate an integral- will be problematic, if I give the function two input arguments.
My detailed explenation:
The p(Xi) is my precalculated Vector with different values.
Is it expedient to do this with the method of passing data?
Very best
Christian
Stephen, good to know. So glad they taught me good code practices in school.
Christian, why don't you just pass in the extra variable?
function Integral = pressure_integral(x,g_x_contact)
Integral = g_x_contact(x).*(x/2)
end
Stephen23
Stephen23 am 2 Mär. 2021
Bearbeitet: Stephen23 am 2 Mär. 2021
"I thought my targeted use for this fuction -to calculate an integral- will be problematic, if I give the function two input arguments."
It isn't problematic at all. This explains what you need:
Christian S.
Christian S. am 4 Mär. 2021
Thank you guys very much!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange

Produkte

Version

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by