combine between numbers and characters in one vector
11 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
i'm working on run length encoding, i use matlab and the input vector is
v=[ 1 2 2 2 2 5 -1 0 0 0 0 -2 -2 -2 -2 -2 7]
the output vector must be
w=[ 1 @ 2 4 5 -1 @ 0 4 @ -2 5 7]
@ is a character that indicates a repetition, then comes the repeated number and the number of repetition my question is : can i combine between characters and numbers in a same vector ?
1 commentaire
Stephen23
le 9 Août 2018
Modifié(e) : Stephen23
le 9 Août 2018
"the output vector must be..."
That is not possible with MATLAB: a numeric array cannot hold a character like that.
"can i combine between characters and numbers in a same vector ?"
Not really, not in the way that you show. Numeric arrays can store character codes, but character codes are just numeric values, so they do not display differently from any other values. You will either have to use a numeric indicator, e.g. NaN, or change how you store your data.
Réponse acceptée
Stephen23
le 9 Août 2018
Modifié(e) : Stephen23
le 9 Août 2018
The simplest solution is to simply mark the number of repetitions for all values: this requires the least processing and can be simply stored in a numeric array:
>> V = [1,2,2,2,2,5,-1,0,0,0,0,-2,-2,-2,-2,-2,7];
>> D = [true,0~=diff(V)];
>> N = diff(find([D,true])); % count group length.
>> Z = V(D); % the first of each group of one value.
>> Z(2,:) = N; % simplest solution: row1=values, row2=repetitions.
Z =
1 2 5 -1 0 -2 7
1 4 1 1 4 5 1
>> reshape(Z,1,[]) % the same in a vector: (1:2:end)=values, (2:2:end)=reps.
ans =
1 1 2 4 5 1 -1 1 0 4 -2 5 7 1
However if you really want to only mark those which are repeated, this works:
>> Z(3,:) = NaN; % add third row
>> C = num2cell(Z([3,1,2],:)); % note row order change using indexing!
>> C([1,3],N==1) = {[]}; % clear for non-repeated
>> [C{:}]
ans =
1 NaN 2 4 5 -1 NaN 0 4 NaN -2 5 7
0 commentaires
Plus de réponses (1)
jonas
le 9 Août 2018
Modifié(e) : jonas
le 9 Août 2018
You cannot mix actual numbers and strings in the same array, but you could store the numbers as strings, or use another identifier, such as NaN, and store everything as numbers. You could also mix numbers and strings in a cell array.
Best solution for you depends on how you want to process this output later.
0 commentaires
Voir également
Catégories
En savoir plus sur Matrix Indexing dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!