MATLAB Answers

Append to an array

3.585 views (last 30 days)
Subhiksha
Subhiksha on 18 Sep 2013
Hi all,
I have a function called details, where the user enters his name, and the details are stored in the array, say "name". Each time a name is entered it should get appended to the array.
At any point, the user can cancel entering the details and do other computations. Then again the user can start entering the details. In this case, it should get appended to the "name" array that is already existing.
At the beginning of the session, the array "name" should be empty.

  1 Comment

Azzi Abdelmalek
Azzi Abdelmalek on 18 Sep 2013
post your code

Sign in to comment.

Accepted Answer

Yatin
Yatin on 16 Oct 2013
Edited: Yatin on 16 Oct 2013
Hi,
A possible solution to your problem could be something like this. Set the array as empty initially(beginning of the session).
nameArray = {};
You can then append the entries in the array as follows:
nameArray = [nameArray, 'Name you want to append'];
This uses the concept of cell array. You might want to refer to the documentation on cell arrays for more information. http://www.mathworks.com/help/matlab/cell-arrays.html

  5 Comments

Show 2 older comments
Steven Lord
Steven Lord on 19 Oct 2018
If you run both commands over and over again, nameArray will keep only the last name entered.
If you run the first command once to initialize the variable then run only the second line repeatedly to append to the cell array, it will do what the original poster asked.
Bill Tubbs
Bill Tubbs on 22 Mar 2020
Sad that this is the only solution since it's not efficient (reallocates memory each iteration) but what can you do... Thanks!
bla bla
bla bla on 13 Apr 2020
@Bill Tubbs maybe try nameArray(end+1) = {'name to be appended'}; should be a more efficient way of doing it

Sign in to comment.

More Answers (1)

Vinaya Babu Yerneni
Vinaya Babu Yerneni on 16 Oct 2020
Firstly you need to clarify whether you need to append strings or integer or string and integer
for only strings
name=input('What is your name? ', 's');
age=input('What is your age? ',"s");
hometown=input('What is your hometown? ', 's');
sport=input('What is your favorite sport? ', 's');
Temptex2=append(name,age,hometown,sport)

  0 Comments

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!