Performing computation using contents stored in a table
1 view (last 30 days)
Show older comments
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 Comments
darova
on 25 Feb 2020
Yes, it's clear now. Thank you
Do you always operate on numbers? Why do you need table?
Answers (1)
darova
on 26 Feb 2020
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 );
See Also
Categories
Find more on Environment and Settings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!