Effacer les filtres
Effacer les filtres

Get Array Number when value changes - Code does not work

1 vue (au cours des 30 derniers jours)
Marv
Marv le 5 Oct 2015
Modifié(e) : Voss le 21 Déc 2023
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

Réponses (1)

Voss
Voss le 21 Déc 2023
Modifié(e) : Voss le 21 Déc 2023
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'})
ans = 2×1 cell array
{'□_1' } {_2'}
In that example, I imagine you'd want:
strcat({'6'; '8'},{'_'},{'1'; '2'})
ans = 2×1 cell array
{'6_1'} {'8_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)
Limits = struct with fields:
field_6_1: [2×1 double] field_8_2: [2×1 double] field_4_3: [2×1 double]

Catégories

En savoir plus sur Dates and Time dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by