Problem with logical indexing

조회 수: 2 (최근 30일)
RP
RP 2019년 4월 24일
댓글: Ajith Thomas 2019년 7월 19일
I'm trying to write a function that will take a row vector of temperatures as input and will give the number of temperatures below 32° as output. I have tried this:
function numfreeze = freeezing(temperatures)
numfreeze = numel(freezing(freezing<32))
end
...but I get the error message "Out of memory. The likely cause is an infinite recursion within the program."
Can someone help me and tell me what this means? When I just use
numfreeze = numel(freezing(freezing<32))
in the command window after setting a vector for "temperatures", it works fine.

채택된 답변

Guillaume
Guillaume 2019년 4월 24일
편집: Guillaume 2019년 4월 24일
freezing is the name of the function. So when you write freezing inside the function, you're telling it to call itself. Of course, once it's called itself, it reexecute that freezing call ad finitum. Hence the infinite recursion.
You probably meant to use the input variable temperatures inside that function
function numfreeze = freeezing(temperatures)
numfreeze = numel(temperatures(temperatures<32))
end
While the above will work, it's not the most efficient. You're deleting all the elements above 32 to then find out how many remain. It be simpler to just count how many true values are in your logical array and not bother with the deletion, so:
function numfreeze = freeezing(temperatures)
numfreeze = nnz(temperatures<32); %you can also use sum instead of nnz
end
  댓글 수: 1
RP
RP 2019년 4월 24일
Thank you so much, this works and I didn't know nnz before!

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

추가 답변 (2개)

Alex Mcaulley
Alex Mcaulley 2019년 4월 24일
I think you have a typo, calling infinite times the function freezing, then:
function numfreeze = freeezing(temperatures)
numfreeze = numel(temperatures(temperatures<32))
end

Ajith Thomas
Ajith Thomas 2019년 7월 19일
function numfreeze=freezing(w)
lowerthan_32=w(w<32);
no_logical_values=lowerthan_32(lowerthan_32>=0);
numfreeze=length(no_logical_values);
end
  댓글 수: 1
Ajith Thomas
Ajith Thomas 2019년 7월 19일
function numfreeze=freezing(w)
lowerthan_32=w(w<32);
numfreeze=numel(lowerthan_32);
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