combine between numbers and characters in one vector
13 次查看(过去 30 天)
显示 更早的评论
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 个评论
Stephen23
2018-8-9
编辑:Stephen23
2018-8-9
"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.
采纳的回答
Stephen23
2018-8-9
编辑:Stephen23
2018-8-9
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 个评论
更多回答(1 个)
jonas
2018-8-9
编辑:jonas
2018-8-9
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 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!