MATLAB: New column

elseifnew columnswitch

Hello,
I work with the below part of a txt file (since the original is huge one):
Stock Date Time Price Volume Stock Category >ETE 04/01/2010 10145959 18.31 500 Big Cap >ETE 04/01/2010 10150000 18.01 70 Big Cap >ETE 04/01/2010 10170000 18.54 430 Big Cap >ABC 04/01/2010 10190000 18.34 200 Big Cap >YYY 04/01/2010 10200000 18.34 100 Big Cap >ETE 04/01/2010 10250000 18.31 40 Big Cap >ETE 04/01/2010 10295959 18.74 215 Big Cap >ETE 04/01/2010 10300000 18.74 500 Big Cap >ETE 04/01/2010 10320000 18.34 500 Big Cap
% I need to create a new variable (column six, let's say 'TRADE'. It's first value will be arbitrarilly asigned to 'BUY' (is there any code to do that?). Then I need its value to be 'BUY' if the row's value of Price(column 4) is higher than the previous row's value of Price. If price is lower, then it would be 'SELL'. In case of equal prices then if value in new column 7 (Trade) of previous row is 'BUY', then it will be 'BUY', otherwise 'SELL' (that's the why I arbitrarilly define the first value),
so the sample will looking like:
Stock Date Time Price Volume Stock Category Trade >ETE 04/01/2010 10145959 18.31 500 Big Cap BUY >ETE 04/01/2010 10150000 18.01 70 Big Cap SELL >ETE 04/01/2010 10170000 18.54 430 Big Cap BUY >ABC 04/01/2010 10190000 18.34 200 Big Cap SELL >YYY 04/01/2010 10200000 18.34 100 Big Cap SELL >ETE 04/01/2010 10250000 18.31 40 Big Cap SELL >ETE 04/01/2010 10295959 18.74 215 Big Cap BUY >ETE 04/01/2010 10300000 18.74 500 Big Cap BUY >ETE 04/01/2010 10320000 18.34 500 Big Cap SELL
Any help?
Thanks in advance,
Panos

Best Answer

I think this does what you want:
Price = randi(10,20,1)
buy = [true;diff(Price)>=0];
idx = find(~diff(Price));
buy(idx+1) = buy(idx);
[Price,buy]
I'm using a logical array buy that is true for "buy" and false for "sell". You could use a nominal array (if you have Statistics Toolbox) to assign arbitrary labels (ie "buy" and "sell"), but logical probably does what you want the easiest.
EDIT: if you really want a column of strings (for output purposes), this will do it:
buysell = cellstr(repmat('Sell',size(Price)));
buysell(buy) = {'Buy'}