I want to populate an empty array, and then access individual elements from within a function.
a = [];
for i=1:10
a(i)=i;
end
function display_a(k)
a = a(k);
disp(a);
end
display_a(5)
Here I receive an error:
'a' undefined near line 8, column 7
Which means that a=a(k) within the function is not recognized as my array a. Any idea on how to pull this off?
I tried declaring a as a global variable. Apart from my understanding that declaring global variables is not a good practice, my function returns the whole array instead of just one, specified element.
Thank you in advance.
function display_a(a,k).a = a(k)because after that the arraya(:)becomes a scalara(unless this is really what you want). Use an intermediate variableb=a(k); disp(b)or even directlydisp(a(k))