Assign values to elements of a matrix with indices less than those specified in an array

Hi,
I'm not really sure how to word my question (hence the confusing title!). What I'm trying to do is take an array of values, like A=[2,4,1,3]
and use it to make a matrix B that looks like;
1 1 1 1
1 1 0 1
0 1 0 1
0 1 0 0
i.e. there are ones for rows lower than the value in the column from A. I can see how I'd do this using a for loop, but we'd like to speed up our (currently very slow) program, so I wondered if anybody had an idea how I could make this vectorised?
Cheers

댓글 수: 4

What is the relation between A and B?
Nothing "magic" comes to mind otomh...sometimes a loop is best. What are you now doing to generate it? The crude would be
B=zeros(max(A)); % preallocate
for i=1:length(B)
B(:,i)=ones(A(i),1);
end
Unless A is huge or you've no preallocated I'd not think this would take long at all. Have you actually profile your code to find out what is the bottleneck or are you guessing about what might be?
Mike
Mike 2013년 10월 20일
편집: Mike 2013년 10월 20일
within each column in B, the value of B is 1 if the row number is less than or equal to the value in A
e.g. the first column of A contains a 2
the first column of B contains 2 1's, then zeros
the last column of A contains a 3
the last column of B contains 3 1's, then zeros
I apologise about my inability to describe this clearly!
Just, forgot the length argument in B...
B=zeros(max(A)); % preallocate
for i=1:length(B)
B(1:A(i),i)=ones(A(i),1);
end

댓글을 달려면 로그인하십시오.

 채택된 답변

Not the best solution, but it should work
A=[2,4,1,3]
B=zeros(max(A),numel(A))
idx=cell2mat(arrayfun(@(x) sub2ind(size(B),(1:A(x)),ones(1,A(x))*x),1:numel(A),'un',0))
B(idx)=1

댓글 수: 3

perfect!
Thanks so much!
I had been messing with sub2ind, but not quite worked out what to do with it!
Or simply
A=[2,4,1,3];
n=max(A);
m=numel(A);
B=zeros(n,m);
for k=1:m
B(1:A(k),k)=1;
end
disp(B)
Yep...simpler is often better. I just forgot to write the explicit length on the fly in original response.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

n = max(A);
nn = numel(A);
p = zeros(n,nn);
p(A + n*(0:nn-1))=1;
out = flipud(cumsum(flipud(p)));

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

질문:

2013년 10월 20일

댓글:

dpb
2013년 10월 20일

Community Treasure Hunt

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

Start Hunting!

Translated by