Clear Filters
Clear Filters

Is it possible to use 'assignin' to append data to an array in the base workspace?

15 views (last 30 days)
I am setting up a GUI where a plot is used to manually select data points. These data points are sent to the base workspace as an array named 'flagged' when the users click an 'export' button. The 'assignin' command is used to accomplish this. This all works fine when when used once. However, many times the users wants/needs to go through this process multiple times. In such cases, the 'flagged' array is overwritten each time. It is preferrable for us to keep all the data.
Does anybody know how to append data from a GUI to the base workspace using assignin or some other command?
Thank You.

Accepted Answer

Image Analyst
Image Analyst on 22 Nov 2023
You'd need to use eval to first get the current values of the variable into a new variable, say existingVar. Then make up your new data and append it then use assignin to send the new variable back into the base workspace:
% Create data.
v1 = [1,2,3];
% Put v into the base workspace.
assignin('base','v1', v1)
% Now make some new variable v2
v2 = [4,5,6];
% Retrieve existing v1
v1 = evalin('base', 'v1')
% Append v2 to v1 and put results in v1.
v1 = [v1, v2]
% Send it back to the base workspace.
assignin('base','v1', v1)
% Verify: double check that v1 is what we expect.
v1 = evalin('base', 'v1')
  2 Comments
Kylen
Kylen on 27 Nov 2023
Thank you, this worked. I had actually tried a version of this myself but ran into trouble with an error ("All tables being horizontally concatenated must have the same number of rows"). Seeing your suggestion typed out helped and I was able to make things work correctly.
Image Analyst
Image Analyst on 27 Nov 2023
Yeah, if it's a table, you would have to use a semicolon instead of a comma
t1 = [t1; t2]
but they'd have to have the same number of columns and with the same column names or else it doesn't make sense. They can have different number of rows though.
Or you can use join or innerjoin or outerjoin which can handle things like differing numbers of rows and columns.

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!