Info

This question is closed. Reopen it to edit or answer.

How to use the index of a matrix in another one?

1 view (last 30 days)
Islam
Islam on 1 Dec 2013
Closed: MATLAB Answer Bot on 20 Aug 2021
EDIT
I have a matrix y(k,sum(counter))=
0 1 0 0 1 0
1 0 0 1 0 0
0 1 0 0 1 0
1 0 0 1 0 0
0 1 0 0 1 0
counter(j,1) =
[ 2
1
3 ]
I want something that says for each j in the counter(j,1) find its value, then sum the columns of y that are equal to the value in the counter.
for counter (1)= 2 , then sum the first (two) columns in y
for counter(2)= 1 , sum the following (one) column ( will stay the same basically)
for counter(3) = 3, sum the following (three) columns in y
y_new = [
1 0 1
1 0 1
1 0 1
1 0 1
1 0 1 ]
  2 Comments
Azzi Abdelmalek
Azzi Abdelmalek on 1 Dec 2013
This is not clear, what is counter? , what does mean (which is equal 2)?

Answers (3)

Wayne King
Wayne King on 1 Dec 2013
You are missing something in your description, summing the first two columns of y does not result in y_new. How did you get a third column of all ones in y_new?
idx = find(counter==1,1,'first');
B = A;
B(:,1) = sum(A(:,1:2),2);
B(:,2) = [];
The above creates a new matrix B with the first column equal to sum of the first two columns of A. But again what you described does not result in y_new

Azzi Abdelmalek
Azzi Abdelmalek on 2 Dec 2013
y=[ 0 1 0 1 1 0
1 0 0 1 0 0
0 1 0 0 1 0
1 0 0 1 0 0
0 1 0 0 1 0]
counter =[2;1;3];
ii=1;
idx1=1;
for k=counter'
idx2=idx1+k-1;
out(:,ii)=sum(y(:,idx1:idx2),2);
idx1=idx2+1;
ii=ii+1;
end
out

Andrei Bobrov
Andrei Bobrov on 2 Dec 2013
Edited: Andrei Bobrov on 2 Dec 2013
iend = cumsum(counter);
ifs = iend - counter + 1;
idx = zeros(iend(end),1);
idx(ifs) = 1;
idx = cumsum(idx);
[ii,jj] = ndgrid(1:size(y,1;),idx);
out = accumarray([ii(:),jj(:)],y(:));
or
out = cell2mat(cellfun(@(x)sum(x,2),mat2cell(y,size(y,1),counter),'un',0));
or
i0 = cumsum(counter);
i1 = i0 - counter + 1;
for ii = numel(counter):-1:1
out(:,ii) = sum(y(:,i1(ii):i0(ii)),2);
end

Tags

Community Treasure Hunt

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

Start Hunting!