필터 지우기
필터 지우기

Replace elements in matrix based on indices stored in another matrix

조회 수: 3 (최근 30일)
LM_BU
LM_BU 2018년 7월 31일
댓글: Star Strider 2018년 7월 31일
I will probably be unable to articulate the problem well.
There are three variables, indicating indices:
a = [3:10, 17:21, 28]; b = [11:13, 22:24, 29:30]; c = [14:16, 25:27];
These are all indices in a categorical fashion (each variable is a category). Now, I want to create a variable to feed into a RepeatedMeasuresModel; hence, I will need some sort of dummy coding. To automate this, I want to have a matrix whose elements are 1, 2 or 3 (thereby representing a/b/c), based on the indices from the said variables.
E.g. conditions = [1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 1, ...., 2, 2]; %n = 30. How do I output this? I have tried logical indexing, but it fails, because the matrices are not the same size. E.g. conditions = 1:30; conditions(conditions==a) = 1;
A side question, how would I, instead of say using 1/2/3 integers, use char arrays instead? For instance, instead of 1, we want to place the "value" 'Category1', 2 = 'Category 2', etc.
Thanks for your support.

채택된 답변

Star Strider
Star Strider 2018년 7월 31일
I am not exactly certain what you want.
Try this:
a = [3:10, 17:21, 28];
b = [11:13, 22:24, 29:30];
c = [14:16, 25:27];
conditions = zeros(1,30); % Preallocate
conditions(a) = 1;
conditions(b) = 2;
conditions(c) = 3
cats = cell(1,30); % Preallocate
cats(a) = {'Category1'};
cats(b) = {'Category2'};
cats(c) = {'Category3'}
conditions =
' 0 0 1 1 1 1 1 1 1 1 2 2 2 3 3 3 1 1 1 1 1 2 2 2 3 3 3 1 2 2 '
cats =
' Category1 Category1 Category1 Category1 Category1 Category1 Category1 Category1 Category2 Category2 Category2 Category3 Category3 Category3 Category1 Category1 Category1 Category1 Category1 Category2 Category2 Category2 Category3 Category3 Category3 Category1 Category2 Category2 '
  댓글 수: 2
LM_BU
LM_BU 2018년 7월 31일
Hi Star, This was indeed the solution. Thank you very much!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Stephen23
Stephen23 2018년 7월 31일
편집: Stephen23 2018년 7월 31일
Just use indexing, which is simple and very efficient:
>> C{1} = [3:10, 17:21, 28];
>> C{2} = [11:13, 22:24, 29:30];
>> C{3} = [14:16, 25:27];
>> cond = [1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 1, 1, 2, 2];
>> Z = C(cond)
  댓글 수: 1
LM_BU
LM_BU 2018년 7월 31일
Hi Steve,
Thank you, but this does not answer my question. C{1..3} hold indices. I want to create another variable (your "cond"), but without manually adding those values myself. The result should be something like cond = 3:30; cond(a) = 1; cond(b) = 2; cond(c) = 3; Basically, I need to "flag" a matrix of 30 columns what category each column represents, based on the indices in a, b, and c.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Operating on Diagonal Matrices에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by