i want to write shorter code

조회 수: 2 (최근 30일)
Luca Re
Luca Re 2023년 9월 1일
편집: Voss 2023년 9월 1일
b=[0 1 1 0 0]
b = 1×5
0 1 1 0 0
n=numel(b);
c=b'
c = 5×1
0 1 1 0 0
repmat(b,n,1)
ans = 5×5
0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0 0 1 1 0 0
repmat(c,1,n)
ans = 5×5
0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0
repmat(b,n,1)|repmat(c,1,n)
ans = 5×5 logical array
0 1 1 0 0 1 1 1 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 0 0

채택된 답변

Voss
Voss 2023년 9월 1일
b=[0 1 1 0 0]
b = 1×5
0 1 1 0 0
b|b.'
ans = 5×5 logical array
0 1 1 0 0 1 1 1 1 1 1 1 1 1 1 0 1 1 0 0 0 1 1 0 0
  댓글 수: 2
Bruno Luong
Bruno Luong 2023년 9월 1일
b|b'
is even shorter. ;-)
Voss
Voss 2023년 9월 1일
편집: Voss 2023년 9월 1일
@Bruno Luong: Very good! And it works the same, since | won't accept non-real operands.
@Luca Re: In case you are interested in the difference:
% when b is real,
b = [0 1 1 0 0];
% b' (complex conjugate transpose) and b.' (transpose) are the same
isequal(b',b.')
ans = logical
1
% when b is non-real,
b = [0 1i 1 0 0];
% b' and b.' are different
isequal(b',b.')
ans = logical
0
% but it doesn't matter in this case because | (or) can't deal with
% non-real operands
try
b|b'
catch e
disp(['error: ' e.message])
end
error: Operands must be real.
try
b|b.'
catch e
disp(['error: ' e.message])
end
error: Operands must be real.
% so for b|b.' (or b|b') to work, b must be real, in which case
% b.' is the same as b' as shown above

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Data Type Identification에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by