필터 지우기
필터 지우기

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

조회 수: 3 (최근 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
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 CenterFile Exchange에서 Logical에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by