alphacentauri
alphacentauri

Reputation: 1020

Append a vector to a Matrix

I have a Matrix

 DataSet(1000,400)

I wish to copy each row into a final matrix initially declared as

FinalDataSet=[]

The rule I followed for copying is as follows which is based upon user input

 For any row i in "DataSet"
      if user enters a character X
          Add to FinalDataSet the vector (X,All Elements of DataSet(i))
      else do nothing

I implemented the following code for the above

n=size(DataSet,1);
for i=1:n
     element=inputdlg('Enter Character');
     if(~isempty(element))
          FinalDataSet=[FinalDataSet;[element DataSet(i,:)]];
     end
 end

(The input dialog, as I observed returns [] if cancel is pressed)

However, when I execute the above code FinalDataSet has the following form

 'H'    [1x400 double]
 'g'    [1x400 double]
 'i'    [1x400 double]

What is the problem here? Is it because I am trying to combine two different types of vectors? How can I obtain a (1000,401) dimension Matrix and not a (1000,2) Matrix?

What I feel is that I either need to store the corresponding ASCII values for the characters or manage a separate vector for the User choice altogether. However, is it possible without the above two methods?? Please Help!!

Upvotes: 1

Views: 268

Answers (2)

Martin
Martin

Reputation: 66

Another possibility is using structures. You can append letters behind the name of your structure to find the corresponding arrays. All arrays placed in different points in the structure can vary in size and don't necassarily have to be the same size like yours. Here's it implemented in your code:

n=size(DataSet,1);
for i=1:n
     element=inputdlg('Enter Character');

     if(~isempty(element))
         FinalDataSet.element=DataSet(i,:)
     end
end

Reading the data from your structure is done by calling the structure with the corresponding element, let's use x for an example here.

xdata = FinalDataSet.x;

What you need to be carefull of is not using the element twice, because you will overwrite previous data. Or implement a test if the element is already present in the array and warns you. Hope this helps.

Upvotes: 0

Dennis Jaheruddin
Dennis Jaheruddin

Reputation: 21563

It took me some time to realize what the problem is. You can indeed not get a matrix including a letter.

IF you really want this, the solution is to simply store everything in a 1000x401 cell array like so:

c =  ['H' num2cell(1:10)]

However then you would give up quite a lot of the convenience/efficiency you get by matrix handling.

Therefore I suggest this alternative:

If you are content with storing the character as a number, here is what you can do:

element = {'H'} % inputdlg returns a 1x1 cell
i=1;
DataSet = rand(1000,400);

v = [element{1}+0 DataSet(i,:)]

To then see which letter it is, you can use char:

char(v(1))

Upvotes: 1

Related Questions