Grouping the Elements of the Array
16 次查看(过去 30 天)
显示 更早的评论
Hello, I have a double array with the element number of 897880. I want to group them like 30000 30000 but it gives me error because of the 897880 divided by 30000 is not an integer. How can I group it like 30000 30000 and the last grouped part as it is, if it is not the multiple of 30000? Thank you.
4 个评论
Image Analyst
2022-6-21
What form are these numbers in? They can't be in a double array because matrices can't have ragged right edges. Maybe you have a cell array. Or do you have one long vector of 897880 elements and you want to make it square with the last few elements padded with zeros?
If you have any more questions, then attach your data and code to read it in with the paperclip icon after you read this:
采纳的回答
Voss
2022-6-21
% Taking your example of an array with 17 elements (rather than 897880),
data = 1:17;
% and you want to group them into groups of 5 (rather than 30000).
group_size = 5;
% You can append NaNs to the end of the data as necessary, to make the
% number of elements a multiple of 5:
% number of elements in data
n_data = numel(data);
% number of groups of 5 necessary
n_groups = ceil(n_data/group_size);
% append NaNs off the end of data, storing the result as new_data
new_data = data;
new_data(end+1:n_groups*group_size) = NaN;
% And finally reshape the NaN-appended data set:
new_data = reshape(new_data,group_size,[]).'
4 个评论
Voss
2022-6-21
It is necessary to have something there. It doesn't have to be a NaN, but it's a good idea to use something so that you can distinguish that part from the rest of the data, i.e., discern where the data stops and the filled-in section begins.
Something must be there because a matrix must be rectangular in shape. It can't be some weird polygon shape with a corner missing. In other words, every row must have the same number of elements (or, put another way, every column must have the same number of elements). This is the defining characteristic of a matrix.
If you want something where the number of elements can vary by row, use a cell array.
更多回答(1 个)
Jan
2022-6-21
x = rand(897880, 1);
nx = numel(x);
len = 300000;
tile = [repelem(len, floor(nx / len)), rem(nx, len)]
xC = mat2cell(x, tile, 1);
2 个评论
Jan
2022-6-21
编辑:Jan
2022-6-21
In your question you have 897880 elements and want 3 groups. Because the last group is smaller than the others, you cannot simply use reshape. Therefore I create 3 different arrays and store them in a cell.
Of course you can store the first groups with the matching sizes in a matrix also:
x = rand(897880, 1);
len = 300000;
nx = numel(x);
match = nx - mod(nx, len);
Groups = reshape(x(1:match), len, []).';
Remainder = x(match:nx).';
size(Groups)
size(Remainder)
另请参阅
类别
在 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!