"if sum" (how operator "sum" is possible next to "if"...?)

조회 수: 2 (최근 30일)
Jinho Lee
Jinho Lee 2022년 6월 18일
답변: Jinho Lee 2022년 6월 18일
I'm trying to undedrstand matlab code for Ising model ("https://kr.mathworks.com/matlabcentral/fileexchange/75149-2d-ising-model")
In the program, there is code like:
if sum(ismember([0:100:iter],i))
I understand ismember but I couldn't understand "if sum"
Q1. Next to "if", there should be logic operator but how can "sum" can be placed
Q2. what is the meaning of sum of logic array, it just number ..?
  댓글 수: 1
per isakson
per isakson 2022년 6월 18일
편집: per isakson 2022년 6월 18일
Read the documation of if, elseif, else carefully and you will find that if some_thing_numerical is allowed. That's because in Matlab if appeared decades before logical.

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

답변 (3개)

Image Analyst
Image Analyst 2022년 6월 18일
The sum can either be 0 or some number. ismember gives you a 1 if the item, i, occurs and 0 if not. It can give you a whole vector os 1's and 0's. The sum counts the number of times there is a 1, and so the if block executes if i is found in the vector [0, 100, 200, ......iter] at least once.

Stephen23
Stephen23 2022년 6월 18일
편집: Stephen23 2022년 6월 18일
"Next to "if", there should be logic operator"
The IF documentation actually states that it must be an expression. It also states that "An expression is true when its result is nonempty and contains only nonzero elements (logical or real numeric). Otherwise, the expression is false."
"but how can "sum" can be placed"
Just as the IF documentation states, if the SUM() returns only non-zero elements then the expression is considered true. Otherwise it will be false.
"what is the meaning of sum of logic array, it just number ..?"
Yes, SUM() just adds up all of the trues (as ones). In this usage, these are equivalent:
IF SUM(logicalarray)
IF ANY(logicalarray)

Jinho Lee
Jinho Lee 2022년 6월 18일
I got it!
Thanks

카테고리

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

태그

Community Treasure Hunt

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

Start Hunting!

Translated by