i want to write shorter code

2 Ansichten (letzte 30 Tage)
shamal
shamal am 1 Sep. 2023
Bearbeitet: Voss am 1 Sep. 2023
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

Akzeptierte Antwort

Voss
Voss am 1 Sep. 2023
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 Kommentare
Bruno Luong
Bruno Luong am 1 Sep. 2023
b|b'
is even shorter. ;-)
Voss
Voss am 1 Sep. 2023
Bearbeitet: Voss am 1 Sep. 2023
@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

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by