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

3 ビュー (過去 30 日間)
Sunyoung Lee
Sunyoung Lee 2016 年 10 月 14 日
編集済み: dpb 2016 年 10 月 14 日
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 Center および File ExchangeCrystals についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by