running for loop gives error " Row index exceeds table dimentions "
1 回表示 (過去 30 日間)
古いコメントを表示
taimour sadiq
2021 年 9 月 7 日
回答済み: Peter Perkins
2022 年 3 月 2 日
i want to extraxt specific range of data from a table names as "Raw", and finally find mean of selected data assigned to variable answer. the below codes works frine for single range, but i want to mention an array of min & max range and so that when a for loop runs it should select new range on every iteration but it gives error " Row index exceeds table dimentions .
Raw = table([1 2 3 4 5 6 7 8 9]',[3.6 3.4 5.3 6.8 8.4 3.6 4.8 8.8 7.3]') % the simple code works fine
minrange = 1; maxrange = 3;
data = table2array(varfun(@(x)((x>=minrange)&(x<=maxrange)), Raw(:,1)));
data = Raw(data,:)
answer = mean(table2array(data(:,2)))
##### #######
Raw = table([1 2 3 4 5 6 7 8 9]',[3.6 3.4 5.3 6.8 8.4 3.6 4.8 8.8 7.3]') % this code gives error when minrange changed
answer = zeros(3,1);
minrange = [1 4]; maxrange = [3 6];
for i = 1:2
data = table2array(varfun(@(x)((x>=minrange)&(x<=maxrange)), Raw(:,1)));
data = Raw(data,:)
answer(i,1) = mean(table2array(data(:,2)))
end
0 件のコメント
採用された回答
Abolfazl Chaman Motlagh
2021 年 9 月 7 日
your minrange and maxrange now are vecotors with two value.if you want to put it in for loop, in data you should mention wich component you want.
Raw = table([1 2 3 4 5 6 7 8 9]',[3.6 3.4 5.3 6.8 8.4 3.6 4.8 8.8 7.3]') ; % this code gives error when minrange changed
answer = zeros(2,1);
minrange = [1 4]; maxrange = [3 6];
for i = 1:2
data = table2array(varfun(@(x)((x>=minrange(i))&(x<=maxrange(i))), Raw(:,1)));
data = Raw(data,:);
answer(i,1) = mean(table2array(data(:,2)));
end
answer
this would solve your problem.
or you could :
Raw = table([1 2 3 4 5 6 7 8 9]',[3.6 3.4 5.3 6.8 8.4 3.6 4.8 8.8 7.3]') ; % this code gives error when minrange changed
answer = zeros(2,1);
minrange = [1 4]; maxrange = [3 6];
data = table2array(varfun(@(x)((x>=minrange)&(x<=maxrange)), Raw(:,1)));
for i = 1:2
data_ = Raw(data(:,i),:);
answer(i,1) = mean(table2array(data_(:,2)));
end
answer
but for an easier way to do this, i suggest: (don't use table)
Raw = [3.6 3.4 5.3 6.8 8.4 3.6 4.8 8.8 7.3]';
minrange = [1 4]; maxrange = [3 6];
for i=1:2
answer(i) = mean(Raw(minrange(i):maxrange(i)));
end
answer
その他の回答 (1 件)
Peter Perkins
2022 年 3 月 2 日
Not sure what purpose the first vector serves, but if it always defines non-overlapping groups, then there's no need for a loop:
>> Raw = table([1 2 3 4 5 6 7 8 9]',[3.6 3.4 5.3 6.8 8.4 3.6 4.8 8.8 7.3]')
>> Raw.Group = [1;1;1;2;2;2;3;3;3]
>> varfun(@mean,Raw,'GroupingVariables','Group','InputVariables','Var2')
ans =
3×3 table
Group GroupCount mean_Var2
_____ __________ ________________
1 3 4.1
2 3 6.26666666666667
3 3 6.96666666666667
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!