combine between numbers and characters in one vector
조회 수: 3 (최근 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에서 Logical에 대해 자세히 알아보기
제품
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!