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

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

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

问题

%% 创建根据两个向量定义大小的零数组,适用于2D和3D。

%% 在2D中设置
% 矩形区域,左下角为[_1,_2]
% 右上角为[_1,_2]

lb_corner = [-1, -2];
rt_corner = [2, 2];

domain_size = rt_corner - lb_corner;

dim = size(domain_size, 2);

nb_pixels = [5, 4]; % [x_1,x_2]中的像素数

%% 网格参数
pixel_size = domain_size ./ nb_pixels;

%% 坐标

if dim == 2
    x_coords = zeros(nb_pixels(1), nb_pixels(2), dim);
elseif dim == 3
    x_coords = zeros(nb_pixels(1), nb_pixels(2), nb_pixels(3), dim);
end

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

%% 在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]; % [x_1,x_2,x_3]中的像素数

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

% 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)的数组。


<details>
<summary>英文:</summary>

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]

lb_corner=[-1,-2]
rt_corner=[2,2]

domain_size=rt_corner - lb_corner; 

dim=size(domain_size,2);

nb_pixels=[5,4]; % number of pixels in [x_1,x_2]

%% Mesh parameters
pixel_size= domain_size./nb_pixels;

%% Coordinates

if dim == 2
    x_coords=zeros(nb_pixels(1),nb_pixels(2),dim);
elseif dim == 3
    x_coords=zeros(nb_pixels(1),nb_pixels(2),nb_pixels(3),dim);

end

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]



I want to replace if condition with something like:

% x_coords=zeros(nb_pixels,dim);

this should create array of size `(nb_pixels(1),nb_pixels(2),dim)` in 2D,
and array of size `(nb_pixels(1),nb_pixels(2),nb_pixels(3),dim)`  in 3D

</details>


# 答案1
**得分**: 2

你可以只是将它们连接在一起,然后将 `zeros` 赋予尺寸数组:

```python
x_coords = zeros([nb_pixels, dim]);
英文:

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

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:

确定