How can I abbreviate this code?
Afficher commentaires plus anciens
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
Réponses (1)
Andrei Bobrov
le 26 Juin 2017
Modifié(e) : Andrei Bobrov
le 26 Juin 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 commentaire
Jan
le 26 Juin 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.
Catégories
En savoir plus sur Creating and Concatenating Matrices dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!