How can i replace a number with its no of ocurrences

2 次查看(过去 30 天)
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]

采纳的回答

Mohammad Abouali
Mohammad Abouali 2015-5-28
编辑:Mohammad Abouali 2015-5-28
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 个评论
Ayesha Maroof
Ayesha Maroof 2015-5-28
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 2015-5-28
编辑:Mohammad Abouali 2015-5-28
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

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Elementary Math 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by