필터 지우기
필터 지우기

a = b<0

조회 수: 9 (최근 30일)
kale
kale 2023년 1월 22일
편집: Voss 2023년 1월 22일
What is the meaning of this line?
...
a = b<0;
c = 3*a;
...
Is a IF condition?

채택된 답변

Voss
Voss 2023년 1월 22일
편집: Voss 2023년 1월 22일
a = b<0;
checks if b is less than 0 and stores the result in a.
If b is a scalar: if b is less than 0, then a will be true; otherwise a will be false.
If b is a non-scalar array: a will be a logical array the same size as b, with each element being true or false, depending on whether the corresponding element in b is less than 0 or not.
Examples:
b = 2;
a = b<0 % false
a = logical
0
b = -2;
a = b<0 % true
a = logical
1
b = 0;
a = b<0 % false
a = logical
0
b = randn(3) % non-scalar array
b = 3×3
0.2296 2.5457 -0.5802 -0.3745 -0.5770 0.2825 -0.8004 0.7450 -1.0347
a = b<0 % 3-by-3 logical array, true where b<0 and false elsewhere
a = 3×3 logical array
0 0 1 1 1 0 1 0 1
Then the next line
c = 3*a;
multiplies a by 3 and stores it in c, so c will be an array the same size as a, with the value 3 where a is true and the value 0 where a is false.
Examples:
b = 2;
a = b<0; % false
c = 3*a
c = 0
b = -2;
a = b<0; % true
c = 3*a
c = 3
b = 0;
a = b<0; % false
c = 3*a
c = 0
b = randn(3) % non-scalar array
b = 3×3
0.0840 0.2037 -0.9633 -0.7413 -1.2592 0.3485 -2.1917 0.0558 -2.0495
a = b<0 % 3-by-3 logical array, true where b<0 and false elsewhere
a = 3×3 logical array
0 0 1 1 1 0 1 0 1
c = 3*a
c = 3×3
0 0 3 3 3 0 3 0 3

추가 답변 (1개)

Torsten
Torsten 2023년 1월 22일
편집: Torsten 2023년 1월 22일
"a" is a logical variable.
It is set to "true" (=1) if b<0, else it is set to "false" (=0).
The next operation c = 3*a works as if "a" was a double variable.
Thus c = 3*1 = 3 if "a" was "true", else c = 3*0 = 0 if "a" was "false".

카테고리

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

Community Treasure Hunt

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

Start Hunting!

Translated by