How do I dynamically assign subsets of array data to unique variables without a loop?

5 ビュー (過去 30 日間)
Brad
Brad 2016 年 11 月 2 日
編集済み: Stephen23 2016 年 11 月 2 日
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
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
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
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.

カテゴリ

Help Center および File ExchangeLogical についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by