Using logically indexed vector in a loop to create another vector

1 次查看(过去 30 天)
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 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