How to search for a condition in all index in a row

조회 수: 1 (최근 30일)
Helena Hjørringgaard
Helena Hjørringgaard 2020년 12월 7일
답변: Parag Jhunjhunwala 2023년 6월 12일
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
KSSV
KSSV 2020년 12월 7일
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 ;

댓글을 달려면 로그인하십시오.

답변 (1개)

Parag Jhunjhunwala
Parag Jhunjhunwala 2023년 6월 12일
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

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by