how can I store for loop result in different row(for each i) and column(for each j given i)?

조회 수: 7 (최근 30일)
this code results in 1*n matrix giving output in a same row altogether. however, I would like to have result divided into different rows for the same given i
for example, if i=19, result should appear in the first row and if i=20, result should appear in the second row and so on
[num, txt, raw] = xlsread('all1month.xlsx');
stock = [];
for i = 19:35;
for j = 2:5677;
if strcmp(raw(i,j), raw(231,4));
stock = [stock raw(i,j+1)];
end
end
end
thanks

답변 (2개)

Marc Jakobi
Marc Jakobi 2016년 10월 14일
편집: Marc Jakobi 2016년 10월 14일
You could do it like this:
stock = nan(17,5676);
rCT = 0; %row counter
cCT = 0; %column counter
maxC = 0; %for shortening (column counter sizes may vary)
for i = 19:35
rCT = rCT + 1;
for j = 2:5677
if strcmp(raw(i,j), raw(231,4))
cCT = cCT + 1;
maxC = max(cCT, maxC);
stock(rCT, cCT) = raw(i,j+1);
end
end
cCT = 0; %reset column counter
end
stock = stock(1:rCT, 1:maxC); %shorten to used values
I would recommend to initialize variables with their maximum possible size and shorten them afterwards. If it's a small data set, you won't notice much of a difference and if it is a large data set, you will avoid having long calculations, only to get an "out of memory" error after hours of the program running.
Another way could be to only increment the row counter if your condition is met:
stock = nan(17,5676);
rCT = 1; %row counter
cCT = 0; %column counter
maxC = 0; %for shortening (column counter sizes may vary)
incRow = false;
for i = 19:35
for j = 2:5677
if strcmp(raw(i,j), raw(231,4))
incRow = true;
cCT = cCT + 1;
maxC = max(cCT, maxC);
stock(rCT, cCT) = raw(i,j+1);
end
end
if incRow
rCT = rCT + 1;
end
incRow = false; %reset incRow
cCT = 0; %reset column counter
end
stock = stock(1:rCT-1, 1:maxC); %shorten to used values

dpb
dpb 2016년 10월 14일
편집: dpb 2016년 10월 14일
Keep another index variable incremented for the purpose--
...
k=0;
for i = 19:35;
k=k+1;
accum = [];
for j = 2:5677;
if strcmp(raw(i,j), raw(231,4));
accum = [accum raw(i,j+1)];
end
stock{k} = accum;
end
end
NB: stock is a cell array because its length may be different by row...
Alternatively, w/o the data to check for certain, it appears you could shorten the above significantly as
k=0;
for i = 19:35;
k=k+1;
ix=strcmp(raw(i,:), raw(231,4)); % logical vector where found
stock{k}=raw(i,ix); % save the found locations
end

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by