running for loop gives error " Row index exceeds table dimentions "
1 次查看(过去 30 天)
显示 更早的评论
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!