How can i replace a number with its no of ocurrences

2 Ansichten (letzte 30 Tage)
i have a matrix=a=[1 0 1 0 1;0 1 1 1 1;1 1 0 1 1;1 1 1 1 1] i want to replace ones by their no of occurences in each row like a=[1 0 2 0 3;0 1 2 3 4;1 2 0 3 4;1 2 3 4 5]

Akzeptierte Antwort

Mohammad Abouali
Mohammad Abouali am 28 Mai 2015
Bearbeitet: Mohammad Abouali am 28 Mai 2015
a=[1 0 1 0 1;0 1 1 1 1;1 1 0 1 1;1 1 1 1 1];
cumsum(a,2).*a
ans =
1 0 2 0 3
0 1 2 3 4
1 2 0 3 4
1 2 3 4 5
  2 Kommentare
Ayesha Maroof
Ayesha Maroof am 28 Mai 2015
thanx alot Mohammad Abouali.i lilttle more help needed.can i shuffle the values now.that zeros remain and its place but rest values shuffles with in a row like [3 0 1 0 2;0 2 1 4 3...] like this
Mohammad Abouali
Mohammad Abouali am 28 Mai 2015
Bearbeitet: Mohammad Abouali am 28 Mai 2015
a=[1 0 1 0 1;0 1 1 1 1;1 1 0 1 1;1 1 1 1 1];
b=cumsum(a,2).*a;
disp('b:')
disp(b)
will print:
b:
1 0 2 0 3
0 1 2 3 4
1 2 0 3 4
1 2 3 4 5
Now shuffling:
shuffle=@(data) data(randperm(numel(data)));
for row=1:size(a,1)
mask=logical(a(row,:));
b(row,mask)= shuffle(b(row,mask));
end
disp('shuffled b:')
disp(b)
will print: (well it is random, so each time prints something different)
shuffled b:
2 0 3 0 1
0 1 3 4 2
1 3 0 2 4
4 5 3 1 2

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Elementary Math finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by