gpt4 book ai didi

arrays - Matlab:使用给定条件更改 3D 数组中的元素

转载 作者:太空宇宙 更新时间:2023-11-03 20:34:29 28 4
gpt4 key购买 nike

我在 Matlab 中有一个 3 维数组 (10x3x3),我想将任何大于 999 的值更改为 Inf。但是,我只想将其应用于此数组的 (:,:,2:3)。

我在网上找到的所有帮助似乎只适用于整个数组,或二维数组的 1 列。我不知道如何将其应用于 3D 阵列。

我试过下面的代码,但是运行后它变成了一个69x3x3的数组,我不太明白为什么。我试图从使用二维数组的人那里复制代码,所以我只是觉得我并不真正理解代码的作用。

A(A(:,:,2)>999,2)=Inf;
A(A(:,:,3)>999,3)=Inf;

最佳答案

一种使用逻辑索引的方法-

mask = A>999;  %// get the 3D mask
mask(:,:,1) = 0; %// set all elements in the first 3D slice to zeros,
%// to neglect their effect when we mask the entire input array with it
A(mask) = Inf %// finally mask and set them to Infs

另一个线性索引 -

idx = find(A>999); %// Find linear indices that match the criteria
valid_idx = idx(idx>size(A,1)*size(A,2)) %// Select indices from 2nd 3D slice onwards
A(valid_idx)=Inf %// Set to Infs

或者另一个使用线性索引,几乎与前一个相同,有效索引在一个步骤中计算,从而使我们成为一个单行 -

A(find(A(:,:,2:3)>999) + size(A,1)*size(A,2))=Inf

关于arrays - Matlab:使用给定条件更改 3D 数组中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28741609/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com