Extracting values of a function into an array

Hey guys!
Hope you are doing well! I am currently working on a project that requires me to nest my functions and to call upon different functions. One such function has three inputs, and one output.
The input varies as it progresses through a loop, which overwrites my output value (so for input 1, it will give output 1, then for input 2 it will provide me output 2, overwriting the first output). I don't want that to happen, and I want to store each output value in an array, as my function calculates the output, such that the input 1 gives me output 1, input 2 gives me output 2, and all of these output values are stored in an array.
I don't want to manually index each element, because its too cumbersome and also because the number of inputs depends on the user, which means I don't know what the index should be anyways!
Thanks in advance for any help!!!!

 Respuesta aceptada

Ameer Hamza
Ameer Hamza el 9 de Sept. de 2020
Editada: Ameer Hamza el 9 de Sept. de 2020
If the size of vector is not too large or execution speed is not a critical consideration then you can use dynamic allocation. Something like this. vector 'a' contains the value returns by each call of myFun
a = [];
while 1
x = input('x: ');
y = input('y: ');
z = input('z: ');
a = [a myFun(x, y, z)];
if upper(input('Do you want to enter again? (Y/N)', 's')) == 'N'
break;
end
end
function a = myFun(x, y, z) % example
a = x + y + z;
end

4 comentarios

Vivek Panchal
Vivek Panchal el 9 de Sept. de 2020
Hello.
I am confused with these two lines: a = [a myFun(x, y, z)]; and function a = myFun(x, y, z)
a = x + y + z; With the first line, why are we saying that a is a value within the array and how would myFun work?
Thanks
myFun is just an example function. It takes 3 inputs and returns 1 output. You can replace it with any other function.
This line
a = [a myFun(x, y, z)];
means that append the output of myFun to the end of the vector and reassign it back to the variable 'a'. After each iteration, the number of elements in vector 'a' increase by 1. An alternative is
a = [];
while 1
x = input('x: ');
y = input('y: ');
z = input('z: ');
a(end+1) = myFun(x, y, z);
if upper(input('Do you want to enter again? (Y/N)', 's')) == 'N'
break;
end
end
function a = myFun(x, y, z) % example
a = x + y + z;
end
Vivek Panchal
Vivek Panchal el 10 de Sept. de 2020
Thank you very much!!! My code is working thanks to you!!! Have an amazing day!!!
Ameer Hamza
Ameer Hamza el 10 de Sept. de 2020
I am glad to be of help!

Iniciar sesión para comentar.

Más respuestas (0)

Categorías

Etiquetas

Preguntada:

el 9 de Sept. de 2020

Comentada:

el 10 de Sept. de 2020

Community Treasure Hunt

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

Start Hunting!

Translated by