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

matrix array assign indexing

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

Best Answer

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