0

I have a data of 512 bits, I want to slice it in 16 equal parts each of 32 bits. How can I do it in MATLAB using a for loop?

example:

inputdata=[1,0,1,0,0,0,0,0,1,1,1,0,0,1,0]

I want:

 outpu1=[1,0,1,0,0] output2=[0,0,0,1,1] output3=[1,0,0,1,0]
Adriaan
  • 17,741
  • 7
  • 42
  • 75
Shubham
  • 1
  • 3

1 Answers1

2
inputdata=[1,0,1,0,0,0,0,0,1,1,1,0,0,1,0];
slices = 3; %// number of slices
slicelength = numel(inputdata)/slices;
kk=1;
for ii = 1:slices
    slicedarray(ii,:) = inputdata(kk:ii*slicelength);
    kk=ii*slicelength+1;
end

now slicedarray will contain your slices, with each row being one slice. You do not want the output variables like you asked for, because dynamic variable names are bad.

Vectorising stuff is faster in MATLAB, thus you can use reshape:

inputdata=[1,0,1,0,0,0,0,0,1,1,1,0,0,1,0];
slices = 3;
slicelength = numel(inputdata)/slices;
slicedarray(slices,slicelength)=0; %// initialise for speed
output = reshape(inputdata,[slices slicelength]);

In both cases the output is:

output =
     1     0     0     1     0
     0     0     0     1     1
     1     0     1     0     0

Copyable for your benefit:

inputdata=rand(512,1);
slicelength = 16;
slices = numel(inputdata)/slicelength;
kk=1;
slicedarray(slices,slicelength)=0;
for ii = 1:slices
    slicedarray(ii,:) = inputdata(kk:ii*slicelength);
    kk=ii*slicelength+1;
end

output = reshape(inputdata,[slices slicelength]);
Community
  • 1
  • 1
Adriaan
  • 17,741
  • 7
  • 42
  • 75
  • Thank Adriaan but i want slices to be stored in different variables, like out1, out2... till out16... I hope u now understnad what's my question. – Shubham Dec 03 '15 at 17:16
  • I understand what you mean perfectly, but you do not want different variables. That's called using "dynamic variable names" which is very, very bad MATLAB practise, see the link I provided. I hope you understand what I mean now... – Adriaan Dec 04 '15 at 12:51
  • 2
    It's not just bad MATLAB practice, it's bad anything practice – sco1 Dec 04 '15 at 13:24