将向量附加到空的 MATLAB 矩阵 [英] Appending a vector to an empty MATLAB matrix

查看:30
本文介绍了将向量附加到空的 MATLAB 矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有将 n 维点 (n >1) 插入矩阵 (myPointMatrix) 的 MATLAB 代码,并且正在考虑如何插入第一个点.

I've got MATLAB code inserting n-dimensional points (n >1) into a matrix (myPointMatrix) and am having thoughts about how to insert the first point.

现在,程序会在插入点之前检查 myPointMatrix 的大小.如果是 1x1,则 myPointMatrix 设置为等于当前点.否则附加当前点.这个 if 语句只有一次为真,但每次我插入一个点时都会评估一次,这种情况非常频繁.

Right now the program checks the size of myPointMatrix before inserting a point. If it is 1x1, myPointMatrix is set equal to the current point. Otherwise the current point is appended. This if-statement is only true once, but is evaluated each time I insert a point, which is very very often.

删除 if 并尝试附加到 myPointMatrix 使 MATLAB 抱怨矩阵维度不一致是可以理解的.删除 if 语句和 myPointMatrix = 0 的初始化会导致 MATLAB 发现 myPointMatrix 未定义.也可以理解.

Removing the if and trying to append to myPointMatrix makes MATLAB understandably complain about matrix dimensions not being consistent. Removing both the if-statement and the inialization of myPointMatrix = 0 causes MATLAB to find myPointMatrix undefined. Also understandable.

如何初始化 myPointMatrix 以便删除 if 语句?或者有其他一些聪明的解决方案吗?

How do I initialize myPointMatrix so that I can remove the if-statement? Or is there some other smart solution?

myPointMatrix = 0;
for x=0:limit
    for y=0:limit
        for z=0:limit
            tempPoint = [x y z];
            if (length(myPointMatrix) == 1)
                myPointMatrix = tempPoint;
            else
                myPointMatrix = [myPointMatrix; tempPoint];
            end
        end
    end
end

推荐答案

使用 myPointMatrix = []; 来初始化矩阵.

Use myPointMatrix = []; to initialize the matrix.

myPointMatrix 越大,追加越慢.它变得越来越慢,因为每次添加一个点时,matlab 都会分配一个新大小的新矩阵,并将旧矩阵 + 新点中的信息复制到新矩阵中.

The bigger myPointMatrix is, the slower appending will be. It gets slower and slower, since for each time you append a point matlab allocates a new matrix of the new size and copies the information from your old matrix + your new point into the new matrix.

然后最好用其最终大小初始化 MyPointMatrix,并将点插入矩阵中的给定位置.

It is then better to initialize MyPointMatrix with its final size, and inserting the points into given positions in the matrix.

这篇关于将向量附加到空的 MATLAB 矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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