繁体   English   中英

在 Matlab 中将向量附加到 3d 矩阵

[英]Append vector to 3d matrix in Matlab

我希望将行向量(以及后来的列向量)附加到现有的x by y x z矩阵。 所以基本上“为原始 3d 矩阵中的每个 z 添加一个新行(在“底部”)。考虑以下简短的 Matlab 程序

appendVector = [1 2 3 4 5]; % Small matrix for brevity. Actual matrices used are much larger.
origMatrix   = ones(5,5,3);
appendMatrix = [origMatrix( ... ); appendVector];

我的问题是:我如何寻址(使用 Matlab 风格的矩阵寻址,而不是“手动”类似 C 的循环) origMatrix( ... ) 以便附加上面的向量? 随意还包括有关如何对列向量执行相同操作的建议(我认为执行后者的正确方法是在 Matlab 中简单地使用 '-operator )。

3D 矩阵中的“行”实际上是一个多维数组。

size(origMatrix(1,:,:))
%   5   3

因此,要附加一行,您需要附加一个5 x 3数组。

toAppend = rand(5, 3);
appendMatrix = cat(1, origMatrix, toAppend);

可以仅附加一个 5 元素向量并指定第三维的索引。 在这种情况下,第三维中所有其他索引的“行”值将用零填充。

appendVector = [1 2 3 4 5];
origMatrix = ones(5,5,3);

appendMatrix = origMatrix;
appendMatrix(end+1, :, 1) = appendVector;

相反,如果您想沿第三维附加相同的向量,您可以使用repmat将您的向量转换为1 x 5 x 3数组,然后附加它。

appendVector = repmat([1 2 3 4 5], 1, 1, size(origMatrix, 3));
appendMatrix = cat(1, origMatrix, appendVector);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM