Clear Filters
Clear Filters

Using logically indexed vector in a loop to create another vector

1 view (last 30 days)
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];

Answers (2)

KSSV
KSSV on 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 Comments
AtoZ
AtoZ on 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)

Sign in to comment.


Andrei Bobrov
Andrei Bobrov on 28 Nov 2018
Edited: Andrei Bobrov on 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

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Products


Release

R2014a

Community Treasure Hunt

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

Start Hunting!