MATLAB Answers

Array Indexing in a for loop

9 views (last 30 days)
I am still a novice in MATLAB. I have some questions regarding the array indexing in for loop. My sample program is as below. It runs as intended
%%classical beamformer
N=15;
steer_step=0.1;
theta=-90:steer_step:90;
for q=1:length(theta)
a(q,:)=exp(-1j*w*sind(theta(q))*(-(N-1)/2:(N-1)/2));.
CBF(1,q)=a1(q,:)*Cxx*a1(q,:)'; % Cxx previously generated Matrix of NxN order
end
So I have some doubts regarding logical application in these lines of the code.
1) a(q,:)=exp(-1j*w*sind(theta(q))*(-(N-1)/2:(N-1)/2));.
Should we use elementwise multiplication .* for sind term since q is an array or the normal multiplication is enough.
For any case when should we use element wise and not element wise operation. I know how it works, but not exactly where to use element wise operation.
2) CBF(1,q)=a1(q,:)*Cxx*a1(q,:)';
When should we use or why should we use CBF(1,q) with indexing and simply 'CBF' without any indexing.
For any case when should we define variable/array in LHS to store the value with or without indexing.

  2 Comments

Stephen Cobeldick
Stephen Cobeldick on 5 Feb 2020
"For any case when should we use element wise and not element wise operation. I know how it works, but not exactly where to use element wise operation"
Matrix operations are for linear algebra, so if you are not doing linear algebra, then use element-wise operations. In almost all cases when beginners don't know what linear algebra is, or what matrix multiplication is, or why matrices have such strange ways of behaving, they should be using element-wise operations.
"When should we use or why should we use CBF(1,q) with indexing and simply 'CBF' without any indexing."
These are two completely different operations:
  1. Use indexing when you want to redefine some/all elements of an array.
  2. Allocate an array to a variable (what you called "without any indexing") when you want to allocate the RHS to a variable.

Sign in to comment.

Accepted Answer

Steven Lord
Steven Lord on 5 Feb 2020
Part 1: when one of the quantities you're multiplying is a scalar, the * and .* operators are equivalent.
x = magic(4)
y1 = 2*x
y2 = 2.*x
isequal(y1, y2) % true
In the specific case you identified, theta is a non-scalar array but theta(q) is one value from that array. That means sind(theta(q)) is a scalar.
This documentation page goes into more detail about the difference between array operations (like .*) and the matrix operations (like *.)
Part 2: "CBF(1, q) = ..." assigns whatever's to the right of the equals sign into the one element in row 1, column q of CBF.
"CBF = ..." overwrites the whole of CBF with whatever's to the right of the equals sign.

  1 Comment

Karthik Nagaraj
Karthik Nagaraj on 5 Feb 2020
Thank you for the swift reply

Sign in to comment.

More Answers (0)

Products


Release

R2019b

Community Treasure Hunt

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

Start Hunting!