Repeating table calculations using pairs of columns

I have a table of data and need to do repeat calculations using two columns at a time. One of the columns is always the same (DOY), the other column changes across the spreadsheet. How can I do this without just doing them pair by pair. I am trying to predict a value based on a fitted straight line equation between 2 points. My code is: id1=find(isnan(x)); id2 =find(isnan(y)); x([id1,id2])=[] y([id1, id2])=[] p=polyfit(x,y,1) u=polyval(p,12)
An example of the data is attached. I am ne to MATLAB so if you have other better suggestions I'd be very happy to hear them!

Answers (1)

It's likely this can be solved using varfun. That takes a function handle and a table and applies the function to each variable in the table. You can tell it which variables in the table to work on (all but the DoY), and you can give it a function handle that uses your DoY variable. something like
t2 = varfun(@(x) myfun(x,t1.DoY), t1, 'InputVariables',2:end)
(assuming DoY is the first variable in t1.

3 Comments

Sorry, I am new to Matlab so don't fully understand this answer.
I'm confused as to what x here is in the context of my data?
My script needs to work on DOY plus each of other variable as a pair - i.e. DOY/variable one then DOY/variable 2 etc across the table and only one value is returned for each pair of columns analysed. My script works when I just look at each pair of columns at once but this method is still fairly slow so I was hoping to make it more efficient. Thanks for your help.
x is just "dummy" name for the variable that varfun is applying your function to. I hope this simple example will help:
>> t = table([1;2;3],[4;5;6],[1;-1;1],'VariableNames',{'X' 'Y' 'Sign'})
t =
3×3 table
X Y Sign
_ _ ____
1 4 1
2 5 -1
3 6 1
>> varfun(@(x) x.*t.Sign,t,'InputVariables',{'X' 'Y'})
ans =
3×2 table
Fun_X Fun_Y
_____ _____
1 4
-2 -5
3 6
Thank you very much, that has it explained it very clearly. I can imagine a lot of applications for this.

Sign in to comment.

Categories

Tags

Asked:

on 9 May 2018

Commented:

on 18 May 2018

Community Treasure Hunt

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

Start Hunting!