How to group values in different indexes (in a matrix) together.
2 次查看(过去 30 天)
显示 更早的评论
I have a 1x4000 matrix of 0s and 1s.
The goal: reformat the matrix so that I group every 3 indexes in this matrix into one index. For example, if my 1x4000 matrix (named myq_stream) has the follwoing data in its first 9 indexes - myq_stream = [1 0 1 0 1 1 1 0 0] - I would want my new matrix (name new_stream) to look like the following - my_stream = [101 011 100].
myq_stream is of type double, so I am not sure how to also maintain the leading zeros in the resulting my_stream. Do I have to change myq_stream to string?
Thank you,
2 个评论
the cyclist
2021-11-8
The best way to do this probably depends on what you need to do as the next step. What do you do with the resulting groups?
Maybe just reshaping the array into Nx3 would be useful?
Side note: How do you want to handle the fact that 4000 is not evenly divisible by 3?
采纳的回答
Dave B
2021-11-8
编辑:Dave B
2021-11-8
Yes, if you want 010 to not be 10, it can't be a double...
You didn't describe what should happen with the last triplet, as 4000 is not divisible by 3.
Here are some options for representing this as triplets, I'd recommend considering using a matrix here as that seems like the idiomatic MATLAB approach (depedning on what you're doing with these data):
x=randi(2,1,4000)-1;
x=[x nan nan]; % make it divisible by 3
y1 = reshape(x,3,[])'; % option 1: just treat it as a matrix, when you want triplet n use y(n,:)
y2 = string(y1).join(''); % option 2: make a bunch of strings
y3 = bin2dec(y2(1:end-1)); % option 3: treat the triplets as binary and convert to decimal
2 个评论
Dave B
2021-11-8
to count frequency of each symbol:
[count,symbol] = histcounts(categorical(y2(1:end-1))); % or clean up your matrix to include the 0 pads
or
[count,s]=histcounts(y3,'BinWidth',1)
symbol=dec2bin(s); %if you want
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Multidimensional Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!