필터 지우기
필터 지우기

Using logically indexed vector in a loop to create another vector

조회 수: 2 (최근 30일)
AtoZ
AtoZ 2018년 11월 28일
편집: Andrei Bobrov 2018년 11월 28일
I have a vector `p=[-3 -2 -1 0 1 2 3]`, and an expression for and for ; and c have values. I want to create a vector . How to write a `for` loop to implement the above statement? The code I wrote to implement the first part of the statement is
k=2; p=[-3 -2 -1 0 1 2 3]; c=1; a=5; b=9;
L=logical(p);
p(L);
for K = 1:numel(L)
if L(K) < 1
L(K) = a*exp(1i*K*k)+b*exp(-1i*K*k)
end
end
However, it returns error "Complex values cannot be converted to logicals". Secondly, the output for p(L) doesn't have the value 0 in it. I did it with a direct way which is not convenient for large vectors.
psi_33 = a*exp(-1i*3*k)+b*exp(1i*3*k);
psi_22 = a*exp(-1i*2*k)+b*exp(1i*2*k);
psi_11 = a*exp(-1i*1*k)+b*exp(1i*1*k);
psi_0 = a+b;
psi_1 = c*exp(1i*k);
psi_2 = c*exp(1i*2*k);
psi_3 = c*exp(1i*3*k);
phi11=[psi_33,psi_22,psi_11,psi_0,psi_1,psi_2,psi_3];

답변 (2개)

KSSV
KSSV 2018년 11월 28일
p=[-3 -2 -1 0 1 2 3] ;
phi = zeros(size(p)) ;
for i = 1:length(p)
if -3<p(i)<1
% phi(i) = your expression
elseif 1<=p(i)<=3
% phi(i) = your expression
end
end
  댓글 수: 4
AtoZ
AtoZ 2018년 11월 28일
@KSSV with your code, I won't need a logical indexing?
AtoZ
AtoZ 2018년 11월 28일
@KSSV For example, for p=-2 using your following code, and comparing the results of phi(2) (from your code) with the manually calculated phi(2) do not match?
Manual
phi_22 = a*exp(-1i*2*k)+b*exp(1i*2*k)
your code:
p=[-3 -2 -1 0 1 2 3] ;
phi = zeros(size(p)) ;
for i = 1:length(p)
if -3<p(i)<1
phi(i) = a*exp(1i*p(i)*k)+b*exp(-1i*p(i)*k);
elseif 1<=p(i)<=3
phi(i) = c*exp(p(i)*k);
end
end
phi(2)

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


Andrei Bobrov
Andrei Bobrov 2018년 11월 28일
편집: Andrei Bobrov 2018년 11월 28일
a = 5;
b = 9;
c = 1;
p = (-3:3)';
k = 2;
out = psifun(a,b,c,k,p);
here psifun - function:
function out = psifun(a,b,c,k,p)
a = [a;c];
b = [b;0];
ii = (p >= 1) + 1;
x = 1i*k.*p;
out = a(ii).*exp(x) + b(ii).*exp(-x);
end

카테고리

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

제품


릴리스

R2014a

Community Treasure Hunt

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

Start Hunting!

Translated by