Azzera filtri
Azzera filtri

Replace elements in matrix based on indices stored in another matrix

2 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

Star Strider
Star Strider il 31 Lug 2018
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 '

Più risposte (1)

Stephen23
Stephen23 il 31 Lug 2018
Modificato: Stephen23 il 31 Lug 2018
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 Commento
LM_BU
LM_BU il 31 Lug 2018
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.

Accedi per commentare.

Categorie

Scopri di più su Operating on Diagonal Matrices in Help Center e File Exchange

Tag

Community Treasure Hunt

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

Start Hunting!

Translated by