필터 지우기
필터 지우기

"Operands to the || and && operators must be convertible to logical scalar values" occurring with integer comparisons

조회 수: 1 (최근 30일)
I have written a piece of code that essentially has this structure:
function [output] = spectralSVD(S,thr)
% Input:
% S: [mxn] complex double
% thr: real double, value between 0 and 100
E_tot = trace(abs(S));
n_sv_max = min(size(S));
n_sv = 0;
E_rec = 0;
while E_rec < thr && n_sv <= n_sv_max
n_sv = n_sv+1;
E_rec = 100*cumsum(diag(abs(S(1:n_sv,1:n_sv))))/E_tot;
end
At this point, the code crashes: "Operands to the and && operators must be convertible to logical scalar values."
So as far as I understood, the && would be appropriate here since both conditionals are single-value comparisons (none of E_rec, thr, n_sv and n_sv_max are vectors or matrices). However, I still get the error message mentioned in the title. I have tried converting all of the aforementioned variables with the uint8() function (even though that does not do exactly what I want), but to no avail. It would appear that I misunderstood the explanation I read in other questions on the same error message.
Could anyone explain me where my thought process is going wrong, and how to appropriately fix my code? It would be very much appreciated!

채택된 답변

Guillaume
Guillaume 2017년 4월 10일
편집: Guillaume 2017년 4월 10일
"both conditionals are single-value comparisons (none of E_rec, thr, n_sv and n_sv_max are vectors or matrices)"
The first time through the while loop, they are. The second time... not so much. See the output of:
S(1:n_sv,1:n_sv)
with n_sv = 0 as you've declared.
The best way for you to solve this sort of problems is to use the debugger to check what the values of the variables actually are as opposed to what you think they are.
I suspect n_sv should start at 1.
  댓글 수: 2
dbmn
dbmn 2017년 4월 10일
This is correct, as your n_sv increases, the size of your E_rec increases accordingly.
You can try this with the following code and putting a debug breakpoint on your while condition
rng(5); spectralSVD(rand(10), 10)
The solution in your case is pretty simple. Just use sum instead of cumsum and you should be fine (cumsum will return a vector if you have a vector as an input).
Floris van den Broek
Floris van den Broek 2017년 4월 10일
Thank you very much for your answer, that makes a lot of sense. I cannot believe I didn't think of that! (Since you posted it in a comment I cannot accept your answer as THE answer, so I will just accept the one you replied on)

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

추가 답변 (1개)

Thorsten
Thorsten 2017년 4월 10일
Check before the while
whos E_rec thr n_sv n_sv_max
I am quite sure that not all variables have Size 1x1 and Class double.

카테고리

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

제품

Community Treasure Hunt

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

Start Hunting!

Translated by