How can I abbreviate this code?
Show older comments
I'd like to abbreviate this long code to a shorter one. I think I can use for and while..
Does anybody know to make it effectively?? Thank you in advance~~
%data = 33 x 300 matrix
p1_1 = zeros(1,300);
p1_2 = zeros(1,300);
p1_3 = zeros(1,300);
p1_4 = zeros(1,300);
p1_5 = zeros(1,300);
p2_1 = zeros(1,300);
p2_2 = zeros(1,300);
p2_3 = zeros(1,300);
p2_4 = zeros(1,300);
p2_5 = zeros(1,300);
p3_1 = zeros(1,300);
p3_2 = zeros(1,300);
p3_3 = zeros(1,300);
p3_4 = zeros(1,300);
p3_5 = zeros(1,300);
for i = 1: 300
p1_1(i) = data(1,5*(i-1)+1);
p1_2(i) = data(1,5*(i-1)+2);
p1_3(i) = data(1,5*(i-1)+3);
p1_4(i) = data(1,5*(i-1)+4);
p1_5(i) = data(1,5*(i-1)+5);
end
for i = 1: 300
p2_1(i) = data(2,5*(i-1)+1);
p2_2(i) = data(2,5*(i-1)+2);
p2_3(i) = data(2,5*(i-1)+3);
p2_4(i) = data(2,5*(i-1)+4);
p2_5(i) = data(2,5*(i-1)+5);
end
for i = 1: 300
p3_1(i) = data(3,5*(i-1)+1);
p3_2(i) = data(3,5*(i-1)+2);
p3_3(i) = data(3,5*(i-1)+3);
p3_4(i) = data(3,5*(i-1)+4);
p3_5(i) = data(3,5*(i-1)+5);
end
Answers (1)
Andrei Bobrov
on 26 Jun 2017
Edited: Andrei Bobrov
on 26 Jun 2017
% Let data -> double array [2500 x 3]
n = 5;
[k0,m] = size(data);
k = k0/m;
p = permute(reshape(data,n,[],m),[3,1,2]);
% here p(2,5,:) - your 'p2_5'
1 Comment
Jan
on 26 Jun 2017
+1. This is much better than the original: Clear, compact, fast, easy to expand, less prone to typos.
@Jiwon Song: Avoid hiding indices in the names of variables. You see how much easier the code is with arrays.
Categories
Find more on Creating and Concatenating Matrices 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!