フィルターのクリア

Using logically indexed vector in a loop to create another vector

1 回表示 (過去 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 Center および File ExchangeMatrices and Arrays についてさらに検索

製品


リリース

R2014a

Community Treasure Hunt

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

Start Hunting!

Translated by