gpt4 book ai didi

matlab - 在 MATLAB 中使用 unique() 重构向量

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

假设 A 是一个包含 4 个不同字符串(每个都有 50 次重复)的 200 项元胞数组。B 是一个包含一些整数的 200 项向量。

我正在使用 [cellNos cellStartInd enumCells ] = unique(A) 并获取 A 中的哪个项目等于唯一字符串之一(enumCells 是一个数组包含整数 1-4,类似于枚举字符串)。

我想使用此信息从 B 创建一个 4x50 值矩阵,以便每一列都将具有特定唯一字符串的值。换句话说,我想将 B reshape 为一个矩阵,其中的列根据 A 中的每个唯一字符串排列。

最佳答案

假设您已经知道会有多少次重复,并且所有字符串都以相同的频率重复,您可以执行以下操作:

%# sort to find where the entries occur (remember: sort does stable sorting)
[~,sortIdx] = sort(enumCells);

%# preassign the output to 50-by-4 for easy linear indexing
newB = zeros(50,4);

%# fill in values from B: first the 50 ones, then the 50 2's etc
newB(:) = B(sortIdx);

%# transpose to get a 4-by-50 array
newB = newB';

或者,以更紧凑的方式(感谢@Rich C)

[~,sortIdx] = sort(enumCells);
newB = reshape(B(sortIdx),50,4)';

关于matlab - 在 MATLAB 中使用 unique() 重构向量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4864628/

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