Find unique values in array

44 次查看(过去 30 天)
mark savage
mark savage 2022-7-16
回答: DGM 2022-7-16
Hi,
I have a 7x700 array, theta, with repeated values in each row of the array. I would like to create a new array which is all the unique values in each row of theta. Simplified example of what I mean:
theta=[1 2 3 1 2 3 1 2 3; 4 5 6 4 5 6 4 5 6; 5 4 2 5 4 2 5 4 2]
desired output=[1 2 3; 4 5 6; 5 4 2]
I'm guessing I'd need a for loop to go through all 7 rows and the 'unique' command but I didn't get the right result.
Thank you

回答(1 个)

DGM
DGM 2022-7-16
Since there's generally no guarantee that the rows have the same number of unique elements, then I wouldn't assume that would work. Unless you can guarantee that for your specific case, then use a cell array to store the output. Since you didn't say why the result wasn't right, I'm just going to guess.
theta = [1 2 3 1 2 3 1 2 3; 4 5 6 4 5 6 4 5 6; 5 4 2 5 4 2 5 4 2]
theta = 3×9
1 2 3 1 2 3 1 2 3 4 5 6 4 5 6 4 5 6 5 4 2 5 4 2 5 4 2
nrows = size(theta,1);
T = cell(nrows,1);
for r = 1:nrows
T{r} = unique(theta(r,:),'stable');
end
celldisp(T)
T{1} = 1 2 3 T{2} = 4 5 6 T{3} = 5 4 2
I suppose it's possible to convert the cell array to a numeric array if it turns out to be rectangular.
T = cell2mat(T)
T = 3×3
1 2 3 4 5 6 5 4 2

类别

Help CenterFile Exchange 中查找有关 Multidimensional Arrays 的更多信息

标签

产品


版本

R2021b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by