two matrix problem

조회 수: 5 (최근 30일)
Mate 2u
Mate 2u 2012년 6월 20일
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]

답변 (3개)

Andrei Bobrov
Andrei Bobrov 2012년 6월 20일
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));

Honglei Chen
Honglei Chen 2012년 6월 21일
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))

Jan
Jan 2012년 6월 21일
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

카테고리

Help CenterFile Exchange에서 Resizing and Reshaping Matrices에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by