Matrix Manipulation

1 view (last 30 days)
Amandeep
Amandeep on 8 Sep 2011
Hi,
From the following matrix:
A = [1; 1; 3; 1; 2; 1; 1; 1; 3; 1; 1; 1; 1; 2; 1; 1; 1; 1; 1; 3; 1; 1; 1; 2; 1; 1; 1; 1; 1; 2; 2; 1; 1; 1; 2; 1; 1; 2; 1; 1; 1; 1; 1; 1; 3; 1; 1; 3; 2; 1; 1; 1; 1; 1; 1; 1; 2; 2; 4; 1; 1; 2; 1; 1; 1; 1; 2; 2; 1; 1; 1; 3]
I want a matrix of (row numbers minus one) where A is greater than 1. Also, if the element in A is 2 for example then B for that element in A will record the (row numbers minus one) once, if it was a 3 then just twice, and so on; therfore B will look like:-
B = [2, 2, 4, 8, 8, 13, 19, 19,....., 71, 71]
Thanks, any help will be great!

Accepted Answer

Paulo Silva
Paulo Silva on 8 Sep 2011
A = [1; 1; 3; 1; 2; 1; 1; 1; 3; 1; 1; 1; 1; 2; 1; 1; 1; 1; 1; 3; 1; 1; 1; 2; 1; 1; 1; 1; 1; 2; 2; 1; 1; 1; 2; 1; 1; 2; 1; 1; 1; 1; 1; 1; 3; 1; 1; 3; 2; 1; 1; 1; 1; 1; 1; 1; 2; 2; 4; 1; 1; 2; 1; 1; 1; 1; 2; 2; 1; 1; 1; 3];
a1=find(A==2)-1; %find the index of the 2
a2=find(A==3)-1; %find the index of the 3
a2=repmat(a2,2,1) %duplicate the 3 indexes
B=sort([a1;a2])'; %join and sort the solution, also transpose
%I transposed B because of your B example
  3 Comments
Paulo Silva
Paulo Silva on 8 Sep 2011
it was on purpose, that way you need to understand my code and add your code to it ;)
Amandeep
Amandeep on 8 Sep 2011
lol cheers

Sign in to comment.

More Answers (1)

Amandeep
Amandeep on 8 Sep 2011
I think I figured it usin arrayfun:
A = [1; 1; 3; 1; 2; 1; 1; 1; 3; 1; 1; 1; 1; 2; 1; 1; 1; 1; 1; 3; 1; 1; 1; 2; 1; 1; 1; 1; 1; 2; 2; 1; 1; 1; 2; 1; 1; 2; 1; 1; 1; 1; 1; 1; 3; 1; 1; 3; 2; 1; 1; 1; 1; 1; 1; 1; 2; 2; 4; 1; 1; 2; 1; 1; 1; 1; 2; 2; 1; 1; 1; 3];
missing = (A==1);
A(missing) = 0;
[row, col, vec] = find(A);
b = arrayfun(@(i) (row(i,1)-1)*(ones(1,vec(i,1)-1)),1:size(row,1),'uniform',0)
b = cat(2,b{:});;
  1 Comment
Andrei Bobrov
Andrei Bobrov on 8 Sep 2011
A1=A-1;
[i1,~,v]=find(A1)
B = cell2mat(arrayfun(@(x,y)x*ones(1,y),i1'-1,v','un',0))

Sign in to comment.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!