Expand matrix in matlab?

I would like to expand a matrix row by row in a conditional expression without initializing the matrix. In C ++ I just use the method std::vector

and push_back

without initializing the vector size in C ++. However, I want to do the same scenario in Matlab. This is my pseudocode

for i = 1:lengt(data)
    if ( condition )
        K = [data(1) data(2) i]
end

K 

      

0


source to share


2 answers


If we assume from the above that data is an Nx2 matrix and that you want to store rows satisfying some condition, then you almost have the correct code to update K without having to initialize it to some size:

K = [];  % initialize to an empty matrix

for i=1:size(data,1)   % iterate over the rows of data
    if (condition)
        % condition is satisfied so update K
        K = [K ; data(i,:) i];
    end
end

K % contains all rows of data and the row number (i) that satisfied condition

      



Note that to get all the elements from a row, we use a colon to say that all the elements in the column are specified in row i .

+2


source


Let's assume some working code is similar to your pseudocode.

%// Original code
for i = 1:10
    if rand(1)>0.5
        data1 = rand(2,1)
        K = [data1(1) data1(2) i]
    end
end

      

Changes for "pushing data without initialization / preallocation":



  • In order to save the data at each iteration, we save the "stacking" data at the selected size. This can be seen as pushing data. For the 2D case, use either "push row pointer" or "push column vector". For this case, we accept the first case.
  • We are not indexing in K using the original iterator, but using a custom iterator that only increments when executed condition

    .

The code below should be specified.

%// Modified code
count = 1; %// Custom iterator; initialize it for the iteration when condition would be satisfied for the first time
for i = 1:10
    if rand(1)>0.5
        data1 = rand(2,1)
        K(count,:) = [data1(1) data1(2) i] %// Row indexing to save data at each iteration
        count = count +1; %// We need to manually increment our custom iterator
    end
end

      

+3


source







All Articles