expand matrix in matlab?

情到浓时终转凉″ 提交于 2020-01-17 05:18:28

问题


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 

回答1:


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.




回答2:


Let us assume some working code to resemble your pseudo-code.

%// 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/pre-allocation":

  1. To save data at each iteration we keeping on "stacking" data along a chosen dimension. This could be thought of as pushing data. For a 2D case, use either a "row vector push" or a "column vector push". For this case we are assuming a former case.
  2. We don't index into K using the original iterator, but use a custom one, that only increments when the condition is satisfied.

The code below must make it clear.

%// 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


来源:https://stackoverflow.com/questions/23963605/expand-matrix-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!