To transfer value of cell in uitable with another cell

2 views (last 30 days)
A uitable is constructed like this:
a=[1 2 3 0;1 2 4 5;0 9 7 0;1 3 4 6]; a=num2cell(a)
First the matrix is like this:
1 2 3 0
1 2 4 5
0 9 7 0
1 3 4 6
Therefore I need to construct the code based on the algorithm below:
1.I need to remove 0 in each row, so the value left in each row do not include zero like matrix below:
1 2 3
1 2 4 5
9 7
1 3 4 6
2.Every row of matrix will divided into two partition, partition C1 and C2.The row will divided by 2, if the element in a row is odd, with the least no of element will put in C1, and the rest in C2.
C1 | C2
1 | 2 3
1 2 | 4 5
9 | 7
1 3 | 4 6
3. C2 in each row will change place with C1 in the next row. If the no of elements C2 more than C1, so it will change the first same no of elements C1, the excess element will keep in initial C2 after elements C1 is placed. If the C1 more than C2, the C1 also do the same thing.
C1 | C2
1 | 1 2 %%value 2&3 change with 2&3
2 3 | 9 5 %% value 4 only change with 9 because cell of C1 below less than C2
4 | 1 %% value 7 change with 1 only because C2 < than C1
7 3 | 4 6 %%last row C2 and first row C1 remain unchanged.
4. Operation 3 need to do 3 cycles.
I hope I can get help to solve my problem as algorithm above.

Accepted Answer

Andrei Bobrov
Andrei Bobrov on 7 Dec 2011
A=a.';
[m,n] = size(a);
C = cell(2,m);
for i1 = 1:m
d = A(:,i1);
k = nnz(d);
k1 = floor(k/2);
d1 = nonzeros(d);
C(:,i1) = {d1(1:k1);d1(k1+1:end)};
end
C2 = reshape(C(2:end-1),2,[]);
n1 = min(cellfun('length',C2));
for j1 = 1:size(C2,2)
n2 = n1(j1);
T = C2{2,j1}(1:n2);
C2{2,j1}(1:n2) = C2{1,j1}(1:n2);
C2{1,j1}(1:n2) = T;
end
Cout = cellfun(@transpose,reshape([C(1), C2(:)',C(end)],2,[]),'un',0)';
variant
A = a';
n = sum(A~=0);
s = bsxfun(@(x,y)[x;y-x],floor(n/2),n);
sm = max(s(:));
Oc = arrayfun(@(x)[ones(x,1);zeros(sm-x,1)],s(:)','un',0);
Om = [Oc{:}];
Om(Om~=0) = A(A~=0);
Dw = reshape(Om(:,2:end-1),sm,2,[]);
s3 = min(reshape(s(2:end-1),2,[]));
for i1 = 1:size(Dw,3)
Dw(1:s3(i1),[2 1],i1) = Dw(1:s3(i1),[1 2],i1);
end
out1 = [Om(:,1),reshape(Dw,sm,[]),Om(:,end)];
outc = reshape(arrayfun(@(x)nonzeros(out1(:,x)).',1:size(out1,2),'un',0),2,[])';
outd = A;
outd(A~=0) = out1(out1~=0);
outd = outd'
  4 Comments
Andrei Bobrov
Andrei Bobrov on 8 Dec 2011
1. You show the code that calls the error.
2. please read about nnz:
>> doc nnz
yue ishida
yue ishida on 8 Dec 2011
Thank you for your information and your code. They're very helpful.

Sign in to comment.

More Answers (0)

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!