Calculation of summation with filtering positive and negative values

11 次查看(过去 30 天)
Hi
I have one matrix with u(i,j,t).
I need calculate sum of the variable like this in each time step.i,j have not folloed an approprate pattern for example the same i or j
sum(t)= u(167,148,t)+u(167,139,t)+u(167,165,t)+u(167,164,t)+u(167,163,t)+..
But,I need an algorithm to seperate positive and negative values.
for example in each time step check the u: if u is positive: sumpositive(t)=u(167,158,t)+u(167,159,t)+u(167,160,t)+u(167,161,t)+u(167,162,t)
if u is negative : sumnegative(t)=iu(167,158,t)+u(167,159,t)+u(167,160,t)+u(167,161,t)+u(167,162,t)
Thanks

回答(1 个)

the cyclist
the cyclist 2023-4-24
% Set seed for reproducibility
rng default
% Some pretend data
u = randn(4,4,3);
% Identify positive u
uIsPos = u >= 0;
% Sum the positive u
sumpositive = sum(u.*uIsPos,3)
sumpositive = 4×4
0.5377 1.3155 4.0673 1.0193 3.3236 0 3.8041 0 1.4090 2.0875 1.0461 1.6031 3.7177 1.9729 3.3478 0.6277
% Sum the negative u
sumnegative = sum(u.*~uIsPos,3)
sumnegative = 4×4
-1.1930 0 -0.1022 -0.8649 -0.8095 -3.2701 -0.2414 -0.8804 -5.2031 -0.4336 -1.3499 -0.1649 0 -1.7115 -0.3034 -1.3520
  4 个评论
JAVAD
JAVAD 2023-4-25
移动:the cyclist 2023-4-25
I try to sum in each time step.
Here u(i,j,t); t is time
what I need is that;
for t= 1:length(time)
sum(t)=u(167,158,t)+u(167,159,t)+u(167,160,t)
end
it works but it cannot seperate positive and negative values.it sums u which can be positive and negative
I need one algorithm
if u>0 ; sum all u+
if u<0; sum all u-
the cyclist
the cyclist 2023-4-25
for t = 1:length(time)
sumpositive(t) = (u(167,158,t).*(u(167,158,t)>0)) + (u(167,159,t).*(u(167,159,t)>0)) + (u(167,160,t).*(u(167,160,t)>0));
sumnegative(t) = (u(167,158,t).*(u(167,158,t)<0)) + (u(167,159,t).*(u(167,159,t)<0)) + (u(167,160,t).*(u(167,160,t)<0));
end
which can be simplified to
for t = 1:length(time)
sumpositive(t) = sum(u(167,158:160,t).*(u(167,158:160,t)>0));
sumnegative(t) = sum(u(167,158:160,t).*(u(167,158:160,t)<0));
end

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Surface and Mesh Plots 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by