필터 지우기
필터 지우기

How to limit a calculation for an array for when the cells in an array are greater than 0

조회 수: 1 (최근 30일)
I'm looking apply an equation and calculate an output - The equation is:
IE = 1367*(1+0.033 .* cos(0.0172024.*DN(i))) .* sin(SOLALT(i));
where DN and SOLALT are both 105120x1 arrays.
I want to use the calculation for IE when SOLALT>0, and set IE = 0 when SOLALT <= 0
how do I achieve this?
I have tried to create a for loop but have been unsuccessful.
for i = 1:length(x)
if SOLALT(i) > 0
IE = 1367*(1+0.033 .* cos(0.0172024.*DN(i))) .* sin(SOLALT(i));
end
end
plot(IE)
x a variable with the value 105120
This is the code I attempted

답변 (2개)

Walter Roberson
Walter Roberson 2021년 3월 21일
Logical indexing.
IE = zeros(size(SOLALT));
mask = SOLALT > 0;
IE(mask) = 1367*(1+0.033 .* cos(0.0172024.*DN(mask))) .* sin(SOLALT(mask));

Cris LaPierre
Cris LaPierre 2021년 3월 21일
You don't need a for loop. Try using a logical array (see Ch 12 of MATLAB Onramp).
IE = 1367*(1+0.033 .* cos(0.0172024.*DN)) .* sin(SOLALT);
IE(SoLALT<=0)=0;
  댓글 수: 1
Walter Roberson
Walter Roberson 2021년 3월 22일
Cris's method can be very effective. The difference between Cris's approach and what I posted is that Cris's approach calculates everywhere and then replaces the unwanted parts, whereas mine does not calculate for the unwanted parts. This has several consequences:
  • if most of the outputs are unwanted, the expense of processing everything can potentially be high
  • but it costs to work conditionally, so especially if most of the outputs are wanted, it can be less expensive to replace only the unwanted ones on output
  • the processing could have side effects (like incrementing counters or writing to files), and sometimes it is important that those side effects not take place for the unwanted locations
  • in some cases, processing at the unwanted locations can create error() conditions, so sometimes it is important to only proceed for the wanted locations

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

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2020b

Community Treasure Hunt

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

Start Hunting!

Translated by