How to add values in coloumn with corresponding of logical array?
5 views (last 30 days)
Show older comments
I have a matrix which is shown in following snipped table.
I have to add the value in colomn no 7 when the logical value as per in last coloumn is 1 with the previous value of coloumn 7.
For example: In 3rd row of last coloumn I have logical value 1 so I can add corresponding value of coloumn 7 i.e, 7.6079 with previous value 4.1703 and replace the 4.1703 with output 11.7782.
For that wrote following code:
% Event is the Matrix as shown in the image.
St = find(Event(:,10)); % Index of ones in last coloumn
m = length(St); % No of instance
n = length(Event);
for i = 1:n-m
if Event(i,10) == 1
s = Event(i,7) + Event(i-1,7);
Event(i-1,7)=s;
Event(i,:)=[];
end
end
This worked for all the cases where logical 1 in last coloumn is followed by 0. But, problem encountered when there are consecutive 1 in last coloumn. The above code is adding the corresponding value of 7th coloumn with respect to last coloumn.
The output should be 77.8971(5.0724+12.730+10.910+19.562+24.285+5.3377). i.e, all the corresponding values of all consecutive 1 should be added with previous 0.
But I'm geting 17.8024 (5.0724+12.730).
0 Comments
Accepted Answer
Jan
on 7 Feb 2023
Edited: Jan
on 7 Feb 2023
Start from the end:
s = 0;
for k = size(Event, 1):-1:1
if Event(k, 10) % You can omit the == 1
s = s + Event(k, 7);
elseif s ~= 0
Event(k, 7) = Event(k, 7) + s;
s = 0;
end
end
% Remove the rows with 1 in column 10 afterwards:
Event(Event(:, 10) == 1, :) = [];
With your approach deleting the i.th row causes troubles, because then the former i+1.th row becomes the new i.th row. But in the next iteration i is increased and the former i+1.th row is not considered ever.
4 Comments
Jan
on 8 Feb 2023
Edited: Jan
on 8 Feb 2023
@Pritam Daundkar: Nope, I definitely get a different result:
Event = [ 0 0 0 0 0 0 5.0724 4 305 0; ...
0 0 0 0 0 0 12.7300 9 2 1; ...
0 0 0 0 0 0 10.9100 7 3 1; ...
0 0 0 0 0 0 19.5620 14 2 1; ...
0 0 0 0 0 0 24.2850 16 3 1; ...
0 0 0 0 0 0 5.3377 4 2 1; ...
0 0 0 0 0 0 4.9985 4 1461 0 ];
s = 0;
for k = size(Event, 1):-1:1
if Event(k, 10) % You can omit the == 1
s = s + Event(k, 7);
elseif s ~= 0
Event(k, 7) = Event(k, 7) + s;
s = 0;
end
end
% Remove the rows with 1 in column 10 afterwards:
Event(Event(:, 10) == 1, :) = [];
Event(:, 7)
So if you get another result, you do not use my code.
A sorter version:
for k = size(Event, 1) - 1:-1:1
Event(k, 7) = Event(k, 7) + Event(k+1, 7) * Event(k+1, 10);
end
Event(Event(:, 10) == 1, :) = [];
More Answers (0)
See Also
Categories
Find more on Resizing and Reshaping Matrices 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!