Get Array Number when value changes - Code does not work
2 次查看(过去 30 天)
显示 更早的评论
This Code works:
A = {1 'Monday'
2 'Monday'
3 'Monday'
4 'Sunday'
5 'Sunday'
6 'Monday'
7 'Monday'
8 'Friday'};
[a,~,c] = unique(A(:,2),'stable');
i1 = [true;diff(c)~=0];
x = accumarray(cumsum(i1),cell2mat(A(:,1)),[],@(x){[min(x);max(x)]});
y = strcat(A(i1,2),{'_'},arrayfun(@(x)sprintf('%d',x),(1:nnz(i1))','un',0));
Limits = cell2struct(x,y,1);
But when I use numbers in the cell, then it does not work anymore:
A = {1 6
2 6
3 8
4 8
5 8
6 8
7 4
8 4};
[a,~,c] = unique(A(:,2),'stable');
i1 = [true;diff(c)~=0];
x = accumarray(cumsum(i1),cell2mat(A(:,1)),[],@(x){[min(x);max(x)]});
y = strcat(A(i1,2),{'_'},arrayfun(@(x)sprintf('%d',x),(1:nnz(i1))','un',0));
Limits = cell2struct(x,y,1);
Can someone help me please ? :-) Thanks
0 个评论
回答(1 个)
Voss
2023-12-21
编辑:Voss
2023-12-21
Three things work differently when you have numbers vs when you have character vectors:
1.) You cannot unique() a cell array of numbers. Make them into a numeric vector first.
2.) Applying strcat() to a number is probably not doing what you want, e.g.:
strcat({6; 8},{'_'},{'1'; '2'})
In that example, I imagine you'd want:
strcat({'6'; '8'},{'_'},{'1'; '2'})
wherein the conversion from numbers {6; 8} to character vectors {'6'; '8'} can be done by
cellfun(@(x)sprintf('%d',x),A(i1,2),'un',0)
or in R2016b or later by
compose('%d',vertcat(A{i1,2}))
But, 3.) Field names in a struct cannot start with a digit; they have to start with a letter. To fix that, I've prepended 'field_' to each field name.
A = {1 6
2 6
3 8
4 8
5 8
6 8
7 4
8 4};
[a,~,c] = unique(vertcat(A{:,2}),'stable');
i1 = [true;diff(c)~=0];
x = accumarray(cumsum(i1),cell2mat(A(:,1)),[],@(x){[min(x);max(x)]});
% cellfun/sprintf method:
y = strcat('field_',cellfun(@(x)sprintf('%d',x),A(i1,2),'un',0),{'_'},arrayfun(@(x)sprintf('%d',x),(1:nnz(i1))','un',0));
% compose method (R2016b or later):
y = strcat('field_',compose('%d',vertcat(A{i1,2})),{'_'},arrayfun(@(x)sprintf('%d',x),(1:nnz(i1))','un',0));
Limits = cell2struct(x,y,1)
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Type Conversion 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!