two matrix problem
1 view (last 30 days)
Show older comments
Hi there, I have 2 matrixes of size 300x1.
One matrix A consists of 1's and -1's, and B consists of positive and negative numbers.
On matrix A we tend to see many 1's and -1's in a row. I want to run a program such that whenever the value of A remains 1 or -1 it does the cumsum of B....but then if the cumsum goes below some value of -0.2 the rest of the A values below will be zero till it changes to -1/1 and so on...
For example the input is
. A=[1; 1; 1; 1; 1; -1 ;-1 ;-1 ;1 ;1 ;1 ;1 ;1]
B=[0.4; -0.2; -0.2; -0.25; 0.6; -0.3; 0.4; 0.2; 0.5; 0.3; -0.8; -0.9; 0.9]
The output should be:
A= [ 1 1 1 1 0 -1 0 0 1 1 1 1 0]
0 Comments
Answers (3)
Andrei Bobrov
on 20 Jun 2012
A=[1; 1; 1; 1; 1; -1 ;-1 ;-1 ;1 ;1 ;1 ;1 ;1];
B=[0.4; -0.2; -0.2; -0.25; 0.6; -0.3; 0.4; 0.2; 0.5; 0.3; -0.8; -0.9; 0.9];
K = -.2;
T = cumsum([true;diff(A > 0) ~= 0]);
d = accumarray(T,B,[],@(x)find(cumsum(x) < K,1,'first'));
N = histc(T,unique(T));
out = A.*cell2mat(arrayfun(@(x,y)[ones(y,1);zeros(x-y,1)] ,N,d,'un',0));
0 Comments
Honglei Chen
on 21 Jun 2012
A=[1; 1; 1; 1; 1; -1 ;-1 ;-1 ;1 ;1 ;1 ;1 ;1];
B=[0.4; -0.2; -0.2; -0.25; 0.6; -0.3; 0.4; 0.2; 0.5; 0.3; -0.8; -0.9; 0.9];
bd = [1;find(diff(A))+1;numel(A)+1];
cell2mat(cellfun(@(x,y) [x(1:find(cumsum(y)<-0.2));...
zeros(numel(x)-find(cumsum(y)<-0.2),1)],mat2cell(A,diff(bd),1),...
mat2cell(B,diff(bd),1),'UniformOutput',false))
0 Comments
Jan
on 21 Jun 2012
And the dull loop:
A = [1; 1; 1; 1; 1; -1 ;-1 ;-1 ;1 ;1 ;1 ;1 ;1];
B = [0.4; -0.2; -0.2; -0.25; 0.6; -0.3; 0.4; 0.2; 0.5; 0.3; -0.8; -0.9; 0.9];
accum = 0;
pivot = A(1);
for i = 1:length(A)
if A(i) == pivot % same A value
if accum >= -0.2
accum = accum + B(i); % accumulation
else % lower limit was hit
A(i) = 0;
end
else % changed A value
accum = B(i); % reset accumulator
pivot = A(i); % remember new value
end
end
0 Comments
See Also
Categories
Find more on Interpolation 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!