Performing computation using contents stored in a table
조회 수: 2 (최근 30일)
이전 댓글 표시
Hi,
I've the following table
t = [1 2 3 4 5 6 7 8 9]';
h = [2 3 4 5 6 7 8 9 10]';
value = [1 2 1 2 1 2 1 2 1]';
tbl = table(t,h,value);
tbl = mergevars(tbl,[1 2]);
I'm filtering the contents of the table using a search value. The contents present in the resulting table is used to perform some operations.
searchvalues = 1:10;
tic
for i = 1:length(searchvalues)
searchval = searchvalues(i);
newtable = tbl(any(tbl.Var1 == searchval, 2), :)
tochange = newtable.Var1(:, 2) == searchval;
newtable.Var1(tochange,:) = fliplr(newtable.Var1(tochange,:));
result(i) = sum((newtable.Var1(:,1) - newtable.Var1(:,2)).*newtable.value);
end
toc
result
I'd like to ask for suggestions on how to speed up the steps carried out in for loop.
I tried the following,
searchvalues = 1:10;
tic
i = searchvalues;
newtable = tbl(any(tbl.Var1 == i, 2), :)
tochange = newtable.Var1(:, 2) == i;
newtable.Var1(tochange,:) = fliplr(newtable.Var1(tochange,:));
result(i) = sum((newtable.Var1(:,1) - newtable.Var1(:,2)).*newtable.value);
end
toc
result
But, this didn't work.
EDIT: what happens in the for loop?
The following contents are stored in a table, in variable 'tbl',
Var1 value
______________
1 2 1
2 3 2
3 4 1
4 5 2
I would like to do the following,
i = 2,
If the variable i is present in tbl.Var1, I would like to retain only those rows and delete the remining rows.
Example,
Var1 value
______________
1 2 1
2 3 2
Also, if i is present in column 2 of Multico, the value in column 2 of tbl.Var1 , the columns are flipped
Th expected output is,
Var1 value
______________
2 1 1
2 3 2
Then, I substract tbl(:,1) - tbl(:,2) , this results in a column vector. Sum of the dot product of this column vector and tbl.value is obtained, stored in variabl result.
I repeat the same for different values of i.
댓글 수: 4
darova
2020년 2월 25일
Yes, it's clear now. Thank you
Do you always operate on numbers? Why do you need table?
답변 (1개)
darova
2020년 2월 26일
Version without tables
var11 = [1 2 3 4 5 6 7 8 9]';
var12 = [2 3 4 5 6 7 8 9 10]';
value = [1 2 1 2 1 2 1 2 1]';
i = 2;
ind = (var11==i) | (var12==i);
% (without replacing columns) tbl(:,1) - tbl(:,2) the same as
result = sum( (2*i-var11-var12).*value.*ind );
참고 항목
카테고리
Help Center 및 File Exchange에서 Environment and Settings에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!