Looking for a matrix, and if there, adding to the end of it

Hello. I'm very new to MatLab so this is most likely a terribly easy question, but I just can't seem to figure it out. I run the same function on several sets of data, and what I would like for it to do is to store certain values into a matrix, let's say "hello", that stays in the workspace so that each set of data will add those values to "hello". Then at the end of analyzing all of the sets of data separately, I can then do an additional analysis on just those values that were put into "hello". So I'm trying to write the code to first check to see if hello is there, and if it isn't, to create it and enter in the values. If it is there, I'd just like to check to see if the values its going to add are already there, and if not, to add them to the end of the matrix. Sounds simple, below is what I have: function(x,y)
if exist('hello','var') == 0
assignin('base','hello',[x;y]);
elseif ismember(x,hello) == 1
disp Already contained
else
hello(end+1,:) = [x;y];
end
So it will create the variable if it's not there, but it just inputs "x" and "y" into the first row and overwrites whatever is there, every time. I'm sure there's a simple solution but I'm too new to have it be obvious to me. Any help would be very appreciated, thanks! -Jesse

 Accepted Answer

assignin('base','hello',[x;y]) is not going to create "hello" in the current workspace unless the current workspace happens to be the base workspace. If you are relying on the current workspace being the base workspace then you don't need to assignin() because you are already there.
Probably you just want
hello = [x;y];

3 Comments

Hi Walter,
Thanks, but I think I accidentally forgot the include the "function" portion of the code. So this is being run in a function, so if I don't specify to do the assignin, the function doesn't appear in the base workspace.
If it _is_ the base workspace you are concerned about, then you need to check whether 'hello' exists in the base workspace, not in the current workspace. Also, you have to ensure that all operations are done on the data as it exists in the base workspace. For example ismember(x,hello) is going to be looking at 'hello' in the current workspace, not the base workspace.
Ah there we go! Thanks that's a huge help!

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!