필터 지우기
필터 지우기

creating a vector from a(:) : b(:) , but one for each index without using loops.

조회 수: 1 (최근 30일)
I have two vectors a=[1,2,3] and b=[6,4,9]. My goal is to generate this(see below) without the use of foor loops (a single command line);
result=[a(1):b(1),a(2):b(2),a(3):b(3)];
The problem is that a and b is varying in size (but size(a)=size(b)=[1,N]).
I`ve tried
result=[a(:):b(:)];
and other variations, but it doesnt do the job. Any idea of how i can achieve this?

채택된 답변

Andrei Bobrov
Andrei Bobrov 2012년 11월 1일
편집: Andrei Bobrov 2012년 11월 1일
a=[1,2,3];
b=[6,4,9];
result = cell2mat(arrayfun(@(x,y)x:y,a,b,'un',0));
ADD
a = randi(150,32,4,4,4); % your 4-D array
idx = {1:32,3,2,1}; % your array with indexs
[i1,i2,i3,i4] = ndgrid(idx{:});
i1 = cell(1,4);
[i1{:}] = ndgrid(idx{:});
result = a(sub2ind(size(a),i1{:}));
  댓글 수: 8
Sean de Wolski
Sean de Wolski 2012년 11월 1일
@Kjetil87, probably not, ind2sub is slow and and gets much slower for big data.
Use the for-loop just make pull out as many computations as you can which it looks like you've done already.
kjetil87
kjetil87 2012년 11월 1일
for those interested i found a way that works.
siz=size(psi_table);
Xn(:,3)=(Xn(:,3)-1)*prod(siz(1:3)); % (l-1)(d3)(d2)(d1)
Xn(:,2)=(Xn(:,2)-1)*prod(siz(1:2)); % (k-1)(d2)(d1)
Xn(:,1)=(Xn(:,1)-1)*siz(1); % (j-1)(d1)
idx=sum(Xn,2)+1; % +1 to start at 4D_matrix(1,j,k,l)
idx_V=repmat(0:31,length(idx),1)+repmat(idx,1,32);
idx_V=idx_V';
idx_V=idx_V(:)';
psi=psi_table(idx_V);
% all operations but the repmat line is basicly 0 cost. And repmat is considerably faster then the for loop indexing ( total of aprox 0.6secs vs 6secs for 2263 calls with a big matrix )

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by