# A for loop with matrix as step

조회 수: 15(최근 30일)
Romain Gippa 2019년 10월 18일
댓글: Romain Gippa 2019년 10월 19일
Hi,
This is my first question on mathworks. I apologize in advance if I am unclear.
I would like to make a for loop of 3 iterations. But my iterations need to be matrices (2000x2). To help you help me, here's what I would like to do, but I know it's not the right way :
A = importdata('CSTR3L_72rpm_50.txt', '\t');
B = importdata('CSTR3L_100rpm_50.txt', '\t');
C = importdata('CSTR3L_400rpm_50.txt', '\t');
injectiontime = [12, 150, 40];
i = 1;
for A:1:C
i = i+1;
A(:,1) = A(:,1) - injectiontime(i);
end
I have to treat a lot of data so it will be really helpfull to me !
Thank you very much for your interest

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

### 채택된 답변

Baium 2019년 10월 18일
편집: Baium 2019년 10월 18일
I am also confused about what you want to do. You said you have multiple data sets. If you want to subtract one injectionTime element at a time from corresponding variable, it would be a similar way to Bob's.
z = [A, B, C, ...];
injectionTime = [12, 150, 40]
for i = 1:size(z, 2)
z(:, i) = z(:, i) - injectionTime(1, i);
end
If you want A, B, C, .., N each to be subtracted by ALL injectionTime elements,
z = [A, B, C, ...];
c = cell2mat(arrayfun(@(x) bsxfun(@minus, z, injectionTime(x)), 1:numel(injectionTime), 'UniformOutput', false));
##### 댓글 수: 1표시숨기기 없음
Romain Gippa 2019년 10월 19일
Thank you !
I didn't know we could put matrices as element (in z here).
However, I had to rush so I did my code the rough way, without loops.
A = importdata('CSTR3L_72rpm_50.txt', '\t');
B = importdata('CSTR3L_100rpm_50.txt', '\t');
C = importdata('CSTR3L_400rpm_50.txt', '\t');
injectionTime = [25, 1160, 18];
Acorr = size(A);
Bcorr = size(B);
Ccorr = size(C);
for i = 1:length(A)-injectionTime(1)
Acorr(i,1) = A(i+injectionTime(1),1) - injectionTime(1);
Acorr(i,2) = A(i+injectionTime(1),2);
end
for i = 1:length(B)-injectionTime(2)
Bcorr(i,1) = B(i+injectionTime(2),1) - injectionTime(2);
Bcorr(i,2) = B(i+injectionTime(2),2);
end
for i = 1:length(C)-injectionTime(3)
Ccorr(i,1) = C(i+injectionTime(3),1) - injectionTime(3);
Ccorr(i,2) = C(i+injectionTime(3),2);
end
I will try to merge the 3 loops in one as you shown.

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

### 추가 답변(1개)

Bob Thompson 2019년 10월 18일
I'm confused what you're trying to do.
From the psuedo code you wrote it looks like you're trying to loop through each of the arrays A, B, and C, and subtract the corresponding value of injectiontime from the first column of each array. This is how I would accomplish that in a more common code.
A = importdata('CSTR3L_72rpm_50.txt', '\t');
B = importdata('CSTR3L_100rpm_50.txt', '\t');
C = importdata('CSTR3L_400rpm_50.txt', '\t');
injectiontime = [12, 150, 40];
A(:,1) = A(:,1)-injectiontime(1);
B(:,1) = B(:,1)-injectiontime(2);
C(:,1) = C(:,1)-injectiontime(3);

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

### Community Treasure Hunt

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

Start Hunting!