# Simple reformat data question

4 visualizzazioni (ultimi 30 giorni)
Rahul il 5 Apr 2012
I have
a=[1:16]
and I need to get
b= 1 2 4 3
5 6 8 7
13 14 16 15
9 10 12 11
have a number of such vectors that I want to convert into this format..
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Risposta accettata

Thomas il 5 Apr 2012
There might be a shorter way of doing this but this is a start..
a=[1:16]
b=reshape(a,4,[])'
c=b(:,3)
b(:,3)=[]
b=[b c]
d=b(3,:)
b(3,:)=[]
b=[b;d]
##### 1 CommentoMostra -1 commenti meno recentiNascondi -1 commenti meno recenti
Rahul il 5 Apr 2012

Accedi per commentare.

### Più risposte (2)

Sean de Wolski il 5 Apr 2012
If you can explain what's going on we might be able to help you with a more general solution. Otherwise, there doesn't appear to be a pattern and the solution is thus:
b = a([1 2 4 3; 5 6 8 7; 13 14 16 15;9 10 12 11])
A=reshape(1:16,4,4)'
B = A;
B([end-1 end],:) = B([end end-1],:);
B(:,[end-1 end]) = B(:,[end end-1]);
##### 2 CommentiMostra NessunoNascondi Nessuno
Rahul il 5 Apr 2012
I have to exchange the last and second last row and last and second last column. This is ok for the example matrix, but I have a number of such vectors that I need to reformat.. I'm trying the above solution by Thomas..
Sean de Wolski il 5 Apr 2012
see update

Accedi per commentare.

Matt Tearle il 5 Apr 2012
How much does this need to generalize? If a might be very long, using a transpose is inefficient. Will the number of elements of a be fixed? If not, will the number of elements of a always be a square (so it can be reshaped into an n-by-n matrix)?
If numel(a) can be large, but will always be square:
A = 1:49; % or whatever
n2 = length(A);
n = sqrt(n2);
idx = mod(0:n:(n*n2-1),n2-1)+1;
B = reshape(A(idx),n,n);
B(n,n) = n2;
B([end-1 end],:) = B([end end-1],:);
B(:,[end-1 end]) = B(:,[end end-1]);
##### 0 CommentiMostra -2 commenti meno recentiNascondi -2 commenti meno recenti

Accedi per commentare.

### Categorie

Scopri di più su Robotics in Help Center e File Exchange

### Community Treasure Hunt

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

Start Hunting!

Translated by