在Matlab中展开矩阵? [英] expand matrix in matlab?

查看:172
本文介绍了在Matlab中展开矩阵?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在不初始化矩阵的情况下在条件语句下逐行扩展矩阵.在C ++中,仅使用std::vectorpush_back方法,而无需在C ++中初始化向量的大小.但是,我想在Matlab中执行相同的方案.这是我的伪代码

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 

推荐答案

如果从上面我们假设数据是Nx2矩阵,并且您只想保存满足某些条件的行,那么您几乎拥有正确的代码即可更新您的 K 矩阵,而不必将其初始化为某个大小:

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

请注意,要从一行获取所有元素,我们使用冒号表示从 i 行获取所有列元素.

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

这篇关于在Matlab中展开矩阵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆