英文:
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]);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论