How do I dynamically assign subsets of array data to unique variables without a loop?
6 次查看(过去 30 天)
显示 更早的评论
I’ve got a 4x5 double array of data that looks like this;
11 1 11 111 1111
22 2 22 222 2222
11 3 33 333 3333
22 4 44 444 4444
I’m attempting to dynamically assign rows of double array data to variables based on the unique values in column 1, using the following code;
clear all;
clc;
% Some random sample data
data = [11 1 11 111 1111; 22 2 22 222 2222; 11 3 33 333 3333; 22 4 44 444 4444];
% Find the unique values in column 1
Unique_Data_Rows = unique(data(:,1));
% Assign rows of data to Subset, then to a unique variable name as doubles.
for i = 1:length(Unique_Data_Rows)
Index{i} = find(data(:,1) == Unique_Data_Rows(i)); %#ok<*SAGROW>
Subset{i} = data(Index{i}, :);
end
Finding the data is not a problem. But assigning the data to individual variables has me wondering if I have a less than ideal approach. In reading the FAQs and several comments, it also seems this is a really bad practice that could lead to a lot of unintended consequences.
For this particular problem, what would be the smart approach when the desired output is comprised of a pair of 2 x 5 double arrays?
Subset1 =
11 1 11 111 1111
11 3 33 333 3333
Subset2 =
22 2 22 222 2222
22 4 44 444 4444
Any ideas are appreciated. Thank you.
2 个评论
Adam
2016-11-2
Well, the question extends to why that is the desired output really. If that absolutely has to be it then you will have to do some ugly coding, but where are these used next that requires them to be in separate variables rather than still all in one?
Stephen23
2016-11-2
编辑:Stephen23
2016-11-2
@Brad: assigning to separate individual variables will be slow and buggy. You will not find any advanced users doing this in their own code, and you will not find any advanced users recommending doing this. Read this to know why:
In almost all cases when beginners wish to assign dynamically to variables the much better solution is to simply learn how to use indexing (perhaps in conjunctions with cell arrays or N-D arrays).
回答(1 个)
KSSV
2016-11-2
编辑:KSSV
2016-11-2
Read about unique. In a single shot you can get the unique numbers and their indices.
[c,ia,ib]= unique(data(:,1));
ia is your required indices, pick the array using data(ia,:). Then you can convert this into cell using mat2cell.
I am not on matlab now, else would have coded it.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Whos 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!