expand matrix in matlab?

CroCo

I would like to expand matrix row by row under a conditional statement without initializing the matrix. In C++, simply I use std::vector and push_back method without initializing the size of the vector in C++. However, I want to do same scenario in Matlab. This is my pseudo code

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

K 
Geoff

If we assume from the above that data is an Nx2 matrix, and that you only want to save the rows that satisfy some condition, then you almost have the correct code to update your K matrix 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 elements from a row, we use the colon to say get all column elements from row i.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related