How can I abbreviate this code?

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

답변 (1개)

Andrei Bobrov
Andrei Bobrov 2017년 6월 26일
편집: Andrei Bobrov 2017년 6월 26일

1 개 추천

% 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

Jan
Jan 2017년 6월 26일
+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.

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Creating and Concatenating Matrices에 대해 자세히 알아보기

질문:

2017년 6월 26일

댓글:

Jan
2017년 6월 26일

Community Treasure Hunt

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

Start Hunting!