# Dimension error in matrix manipulation

1 view (last 30 days)
Amandeep on 31 Aug 2011
Hi, trying to figure out why this doesn't work and how to make it work:-
looktime2= [1 16; 2 55; 2 61; 2 66; 2 68; 5 20; 6 60; 8 47; 8 83; 8 105; 9 72; 10 44; 10 57]
t2 = [true;diff(looktime2(:,1))~=0]; t2 = [t2,looktime2(:,2)];
t2 = [1 16; 1 55; 0 61; 0 66; 0 68; 1 20; 1 60; 1 47; 0 83; 0 105; 1 72; 1 44; 0 57]
Rmatrix is a 10 by 121 matrix
for i = 1:size(t2,1)
for j = 1
if t2(i,j)==1
sd(i,j) = Rmatrix(looktime2(i,j),1:t2(i,j+1));
end
if t2(i,j)==0
sd(i,j) = Rmatrix(looktime2(i,j),t2(i-1,j+1):t2(i,j+1));
end
end
end
When I press enter I get an Subscripted assignment dimension mismatch error , but I'm not sure how to get it to work.
Any help will be much appreciated. Thanks

Andrei Bobrov on 31 Aug 2011
that want to get?
Andrei Bobrov on 31 Aug 2011
error in the code
element double array assign vector

Andrei Bobrov on 31 Aug 2011
variant 1 (use 'arrayfun')
t = [true;diff(looktime2(:,1))~=0];
idx = [0;looktime2(1:end-1,2)];
idx(t)=1;
idx2 = [idx looktime2(:,2)];
di = diff(idx2,1,2)+1;
sd = arrayfun(@(i1)[Rmatrix(looktime2(i1),idx2(i1,1):idx2(i1,2)) zeros(1,max(di)-di(i1))],1:numel(t),'un',0);
sd=cat(1,sd{:});
variant 2 (use loop)
t = [true;diff(looktime2(:,1))~=0];
idx = [0;looktime2(1:end-1,2)];
idx(t)=1;
idx2 = [idx looktime2(:,2)];
di = diff(idx2,1,2)+1;
nt = numel(t);
sd = zeros(nt,max(di));
for i1 = 1:nt
sd(i1,1:di(i1)) = Rmatrix(looktime2(i1),idx2(i1,1):idx2(i1,2));
end
variant 3 (vectorization with use 'bsxfun')
l=looktime2';
t = [true diff(l(1,:),1,2)~=0];
idx = [0,l(2,1:end-1)].*~t+t;
di = diff([idx; l(2,:)])+1;
mdi = max(di);
sdt = zeros(mdi,numel(t));
sz = size(Rmatrix);
lm = bsxfun(@and,bsxfun(@le,(1:sz(2))',l(2,:)),bsxfun(@ge,(1:sz(2))',idx));
i1=bsxfun(@times,lm,l(1,:));
j1 = bsxfun(@times,(1:sz(2))',lm);
sdt(bsxfun(@le,(1:mdi)',di)) = Rmatrix(sub2ind(sz,i1(lm), j1(lm)));
sd = sdt';
looktime2= [1 16; 2 55; 2 61; 2 66; 2 68; 5 20; 6 60; 8 47; 8 83; 8 105; 9 72; 10 44; 10 57];
t2 = [true;diff(looktime2(:,1))~=0];
t2 = [t2,looktime2(:,2)];
%t2 = [1 16; 1 55; 0 61; 0 66; 0 68; 1 20; 1 60; 1 47; 0 83; 0 105; 1 72; 1 44; 0 57]
%Rmatrix is a 10 by 121 matrix
sd = nan(size(Rmatrix));
for i1 = 1:size(t2,1)
if t2(i1,1)
k = 1:t2(i1,2);
sd(i1,1:numel(k)) = Rmatrix(looktime2(i1,1),k);
else
k = t2(i1-1,2):t2(i1,2);
sd(i1,1:numel(k)) = Rmatrix(looktime2(i1,1),k);
end
end
sd = sd(:,~all(isnan(sd)));

#### 1 Comment

Amandeep on 1 Sep 2011
Thanks for the help

zohar on 31 Aug 2011
Hi Amandeep,
This is the problem
sd(i,j) = Rmatrix(looktime2(i,j),1:t2(i,j+1));
Subscripted assignment dimension mismatch.
Rmatrix(looktime2(i,j),1:t2(i,j+1)) is vector , and sd(i,j) is 1x1 you can not do that.
Have fun