Replace elements in matrix based on indices stored in another matrix

2 次查看(过去 30 天)
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 '

更多回答(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