0
votes

I need to make a loop in which I need to add value on the end of the vector, so everytime i need to use (end+1), but i need to do it a few time and i don't want to make a lot of tables for this. In this way I need array of vectors like for example in c++. In c++ u use just [1][2] for example to get to this and it's fine but I don't know how to do it in MATLAB. I can't just make static matrix, beacuse my points are generating in while true loop and I draw plots in real time. I was trying something like this:

tab = [4, []];

but it doesn't work. Any ideas? Thanks

2

2 Answers

1
votes

As far as I know this sort of situation is difficult to deal with in Matlab. You can have a array of verctors, since the inner verctors are from the same size, otherwise you'll get an error:

>> a = [2];
>> b = [2,3,4]
b =
     2     3     4
>> c = [a;b]
Error using vertcat
Dimensions of arrays being concatenated are not consistent. 

Now, if a has the same size o b...:

>> a = [2,2,3];
% with ; be is put in a new row
>> c = [a;b]
c =
     2     2     3
     2     3     4
% using , or space the concatenation is horizontal
>> c = [a,b]
c =
     2     2     3     2     3     4
>> c = [a b]
c =
     2     2     3     2     3     4

If you want to just append values to c, just do:

>> c = [c 9]
c =
     2     2     3     2     3     4     9

I recommend you use the cell structure, if possible. You need to previously define the cell array but it can store several vectors of different sizes:

>> cell1 = cell(2)
cell1 =
  2×2 cell array
    {0×0 double}    {0×0 double}
    {0×0 double}    {0×0 double}
>> cell1{1} = c
cell1 =
  2×2 cell array
    {1×7 double}    {0×0 double}
    {0×0 double}    {0×0 double}
>> cell1{2} = a
cell1 =
  2×2 cell array
    {1×7 double}    {0×0 double}
    {1×3 double}    {0×0 double}
>> cell1{2}
ans =
     2     2     3

I hope this helps you...

0
votes

An alternative to cell arrays is to use structure arrays. For example, you can define

a = [2];
b = [2,3,4]
c = [b;b]
d = [a,b]

And then set up a structure like below. It negates working with curly brackets

myStruct = struct()
myStruct(1).myVector = a
myStruct(2).myVector = b
myStruct(1).myVector2 = c
myStruct(2).myVector2 = d

Then r_b and r_c below "pull out" b and c

r_b = myStruct(2).myVector
r_c = myStruct(1).myVector2