将向量附加到空的MATLAB矩阵 [英] Appending a vector to an empty MATLAB matrix
问题描述
我已经获得了将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 = [];
初始化矩阵.
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屋!