在单个语句中声明多维数组

发布于 2024-10-23 19:00:51 字数 288 浏览 1 评论 0原文

假设我想用一条语句创建一个维度为 3×4×4 的矩阵 A(即一个等式,没有任何串联),如下所示:

%// This is one continuous row
A = [ [ [3 3 4 4], [8 11 8 7], [4 4 6 7], [4 7 6 6] ];  ...
      [ [3 2 4 2], [9 6 4 12], [4 3 3 4], [5 10 7 3] ]; ...
      [ [2 2 1 2], [3 3 3 2], [2 2 2 2],  [3 3 3 3] ] ]

Let's say I want to create a matrix A with dimensions 3×4×4 with a single statement (i.e one equality, without any concatenations), something like this:

%// This is one continuous row
A = [ [ [3 3 4 4], [8 11 8 7], [4 4 6 7], [4 7 6 6] ];  ...
      [ [3 2 4 2], [9 6 4 12], [4 3 3 4], [5 10 7 3] ]; ...
      [ [2 2 1 2], [3 3 3 2], [2 2 2 2],  [3 3 3 3] ] ]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ゃ懵逼小萝莉 2024-10-30 19:00:51

您可以使用 cat 来“分层”例如,沿第三维的二维矩阵:

A = cat(3, ones(4), 2*ones(4), 3*ones(4));

从技术上讲,这是串联,但它仍然只是一个赋值。

CATLAB

You can use cat to "layer" 2-D matrices along the third dimension, for example:

A = cat(3, ones(4), 2*ones(4), 3*ones(4));

Technically this is concatenation, but it's still only one assignment.

CATLAB

ゞ记忆︶ㄣ 2024-10-30 19:00:51

连接运算符 [] 仅适用于二维,例如 [ab] 水平连接或 [a; b] 垂直连接。要创建更高维度的矩阵,您可以使用reshape 函数,或初始化矩阵您想要的大小,然后用您的值填充它。例如,您可以这样做:

A = reshape([...], [3 4 4]);  % Where "..." is what you have above

或者这样:

A = zeros(3, 4, 4);  % Preallocate the matrix
A(:) = [...];        % Where "..." is what you have above

The concatenation operator [] will only work in 2 dimensions, like [a b] to concatenate horizontally or [a; b] to concatenate vertically. To create matrices with higher dimensions you can use the reshape function, or initialize a matrix of the size you want and then fill it with your values. For example, you could do this:

A = reshape([...], [3 4 4]);  % Where "..." is what you have above

Or this:

A = zeros(3, 4, 4);  % Preallocate the matrix
A(:) = [...];        % Where "..." is what you have above
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文