Reputation: 11
I need to combine some elements into one element of a row matrix in MATLAB. For example, my matrix is
[1 2 3 4 5 6 7 8]
. I want to transform the matrix like [1234 5678]
. Please help me do this.
Upvotes: 1
Views: 1445
Reputation: 30579
Consider the following anonymous function for a generalized numeric solution for combining single digits:
combineDigits = @(x) x*(10.^(length(x)-1:-1:0)).';
Each element of x
must be on [0,9]
(i.e. single digits). For your example input:
>> x = [1 2 3 4 5 6 7 8]
x =
1 2 3 4 5 6 7 8
>> x1 = x(1:4); x2 = x(5:end);
>> combineDigits(x1)
ans =
1234
>> combineDigits(x2)
ans =
5678
>>
The anonymous function combinedDigits
can be applied with any general utility function, such as cellfun
, to process blocks of data. For example, consider the 2x8
matrix M
of digits, partitioned into a 2x2
cell array of 1x4
digit arrays:
>> M = randi(9,2,8)
M =
4 8 6 8 7 7 6 7
9 9 1 9 7 4 2 1
>> Mpartitioned = mat2cell(M,[1 1],[4 4]) % specify ANY valid partitioning here
Mpartitioned =
[1x4 double] [1x4 double]
[1x4 double] [1x4 double]
>> Mcompacted = cellfun(combineDigits,Mpartitioned)
ans =
4868 7767
9919 7421
Upvotes: 3
Reputation: 2828
First define your values in a numeric array:
a = [1 2 3 4 5 6 7 8];
Next convert to a string:
b = num2str(a);
Now remove all the spaces:
b(find(b == ' ')) = '';
Insert an empty space in the middle and then convert back to a numeric array (I think this is what you want(?)):
c = str2num([b(1:4),' ',b(5:end)]);
So that
>> c(1)
ans =
1234
>> c(2)
ans =
5678
Edit: Added 'end' to cover an arbitrary range.
Upvotes: 1
Reputation: 4768
It depends. If you can guarantee that your row will always be a multiple of 4, you could do the following:
reshape(sum(bsxfun(@times,reshape(Q',4,[])',[1000,100,10,1]),2),[],size(Q,1))';
What this does is reshape
the matrix like so:
[1 2 3 4 5 6 7 8 -> [1 2 3 4
8 7 6 5 4 3 2 1] 5 6 7 8
8 7 6 5
4 3 2 1]
We then multiple each row by [1000,100,10,1]
and sum each row:
[1 2 3 4 [1000 200 30 4 [1234
5 6 7 8 -> 5000 600 70 8 -> 5678
8 7 6 5 8000 700 60 5 8765
4 3 2 1] 4000 300 20 1] 4321]
Finally we reshape the matrix again to get back to the original shape.
[1234 [1234 5678
5678 -> 8765 4321]
8765
4321]
Upvotes: 1
Reputation: 9075
You can do it as following:
a=[1 2 3 4 5 6 7 8];
vec1=a(1:4) %put a suitable number here
vec1=num2str(vec1);
vec1(ismember(vec1,' ')) = [];
vec1=str2double(vec1);
Similarly, perform the above sequence of operation on the latter half of the vector and simply concatenate them in the final vector.
Note: This solution works only for a row vector as you mentioned in the question (you mentioned row matrix, but I assume this is what you meant).
Upvotes: 1