How to search for a condition in all index in a row
3 views (last 30 days)
Show older comments
Hello,
I have quite a big matrix where I need it to find the next number in a row smaller than 45.20
e.g.
0.7 45.03 45.15 44 44
0.4 45.20 44 44 44
0.5 45.20 44.3 44 44
0.38 45.20 44.9 44 44
The bold marking i is our point of interest:
What I need is: 0,7 is added to 45,03, and if ans i larger than 45,20, the surplus is added to 45,15. If this again results in a surplus, this is added to 44 (i-1,j+1) and so forth.
The correct answer should be:
0.7 45.03 45.15 44 44
0.4 45.20 45.20 44.48 44
0.5 45.20 44.20 44.88 44
0.38 45.20 45.2 45.2 44.18
Since I have a large matrix I cannot just use (which is my currently code)
if A(i,j-1) == 45.20 && A(i-1,1) + A(i-1,j-1) > 45.20
A(i,j) = A(i-1,1) + A(i-1,j-1) - 45.20 + A(i-1,j);
if A(i,j) > 45.20
A(i,j+1) = A(i,j+1) - 45.20 + A(i-1,j+1);
A(i,j) = 45.20;
end
end
because it gets the wrong answer in colums later on. I therefore need it to search for the next value smaller than 45.20 and then fill it up.
1 Comment
KSSV
on 7 Dec 2020
Read about logical indexing. You need not to use a loop. At a stretch you can get all the indices which are less than 45.20
idx = A(:,2)<=45.20 ;
Answers (1)
Parag Jhunjhunwala
on 12 Jun 2023
Below is the sample code to address the problem you are facing.The approach to the implementation is covered in comments in the code.
% Traverse the rows of the matrix from top to bottom excluding the last row
for i=1:n-1
% Initialize the remainder value as the value at first column of the ith row
rem=A(i,1);
% Traverse the columns of the ith row starting from the 2nd column
for j=2:m
% If the remainder becomes 0 move on to the next row iteration
if(~rem)
break;
end
% if the sum of remainder and the value at ith row and jth column is greater than 45.2(stored as
% val),assign val to the element just below it and update the remainder otherwise assign the sum
% to the element just below it and move on to the next row iteration(by making remainder 0)
if(rem+A(i,j) >= val)
A(i+1,j)=val;
rem=rem+A(i,j)-val;
else
A(i+1,j)=rem+A(i,j);
rem=0;
end
end
end
0 Comments
See Also
Categories
Find more on Logical in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!