如何分配一个由两个向量定义大小的数组?

huangapple go评论124阅读模式
英文:

How to allocate an array with a size defined by two vectors?

问题

  1. %% 创建根据两个向量定义大小的零数组,适用于2D3D
  2. %% 2D中设置
  3. % 矩形区域,左下角为[_1_2]
  4. % 右上角为[_1_2]
  5. lb_corner = [-1, -2];
  6. rt_corner = [2, 2];
  7. domain_size = rt_corner - lb_corner;
  8. dim = size(domain_size, 2);
  9. nb_pixels = [5, 4]; % [x_1x_2]中的像素数
  10. %% 网格参数
  11. pixel_size = domain_size ./ nb_pixels;
  12. %% 坐标
  13. if dim == 2
  14. x_coords = zeros(nb_pixels(1), nb_pixels(2), dim);
  15. elseif dim == 3
  16. x_coords = zeros(nb_pixels(1), nb_pixels(2), nb_pixels(3), dim);
  17. end

在三维中,向量看起来是这样的:

  1. %% 3D中设置
  2. lb_corner = [-2, -2, -2];
  3. rt_corner = [2, 2, 2];
  4. domain_size = rt_corner - lb_corner;
  5. dim = size(domain_size, 2);
  6. nb_pixels = [5, 4, 5]; % [x_1x_2x_3]中的像素数

我想将if条件替换为以下内容:

  1. % x_coords = zeros(nb_pixels, dim);

这将在2D中创建大小为(nb_pixels(1), nb_pixels(2), dim)的数组,
在3D中创建大小为(nb_pixels(1), nb_pixels(2), nb_pixels(3), dim)的数组。

  1. <details>
  2. <summary>英文:</summary>
  3. I want to create zeros of size defined by two vectors, which will work in 2D and 3D.

%% Setting in 2D
% rectangular domain with left bottom corner [_1,_2]
% and right top corner [_1,_2]

  1. lb_corner=[-1,-2]
  2. rt_corner=[2,2]
  3. domain_size=rt_corner - lb_corner;
  4. dim=size(domain_size,2);
  5. nb_pixels=[5,4]; % number of pixels in [x_1,x_2]

%% Mesh parameters
pixel_size= domain_size./nb_pixels;

%% Coordinates

  1. if dim == 2
  2. x_coords=zeros(nb_pixels(1),nb_pixels(2),dim);
  3. elseif dim == 3
  4. x_coords=zeros(nb_pixels(1),nb_pixels(2),nb_pixels(3),dim);
  5. end
  1. In three dimensions the vectors would look like this:,

%% Setting in 3D
lb_corner = [-2,-2,-2]
rt_corner = [2,2,2]
domain_size=rt_corner - lb_corner;

dim=size(domain_size,2);
nb_pixels=[5,4,5]; % number of pixels in [x_1,x_2,x_3]

  1. I want to replace if condition with something like:

% x_coords=zeros(nb_pixels,dim);

  1. this should create array of size `(nb_pixels(1),nb_pixels(2),dim)` in 2D,
  2. and array of size `(nb_pixels(1),nb_pixels(2),nb_pixels(3),dim)` in 3D
  3. </details>
  4. # 答案1
  5. **得分**: 2
  6. 你可以只是将它们连接在一起,然后将 `zeros` 赋予尺寸数组:
  7. ```python
  8. x_coords = zeros([nb_pixels, dim]);
英文:

You can just concatenate them and hand zeros the size array:

  1. x_coords=zeros([nb_pixels,dim]);

huangapple
  • 本文由 发表于 2023年3月10日 00:05:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75687162.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定