Effacer les filtres
Effacer les filtres

Using logically indexed vector in a loop to create another vector

2 vues (au cours des 30 derniers jours)
AtoZ
AtoZ le 28 Nov 2018
Modifié(e) : Andrei Bobrov le 28 Nov 2018
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];

Réponses (2)

KSSV
KSSV le 28 Nov 2018
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 commentaires
AtoZ
AtoZ le 28 Nov 2018
@KSSV with your code, I won't need a logical indexing?
AtoZ
AtoZ le 28 Nov 2018
@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)

Connectez-vous pour commenter.


Andrei Bobrov
Andrei Bobrov le 28 Nov 2018
Modifié(e) : Andrei Bobrov le 28 Nov 2018
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

Catégories

En savoir plus sur Logical dans Help Center et File Exchange

Produits


Version

R2014a

Community Treasure Hunt

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

Start Hunting!

Translated by