# dot product and indexing

4 views (last 30 days)

Show older comments

I am reviewing this code and I do not undestand what this code means and how the dot operation work.

Can you please explain with some example ?

NCol = [

1 3 1 2 4 3 5 2 3 1 2 5 ]

NRow = [

1 1 2 2 2 3 3 4 4 5 5 5 ]

c=(NCol(1:k-1) == NRow(k)) .* (NRow(1:k-1) == NCol(k))

##### 0 Comments

### Answers (2)

Sulaymon Eshkabilov
on 21 Oct 2021

The explantion is as follows:

% Step 1. Comparing every individual value (element of) of NCol row vector (row matrix)

% with the k-th (the last one) element of NRow (i.e. 5) whether their are equal or not.

% If equal then, the result will be 1 (true); otherwise, 0 (false)

(NCol(1:k-1) == NRow(k))

% Step 2. Similar to Step 1, every individual value (element of) of

% NRow row vector (row matrix) with the kth (the last one) element of NCol (row vector)

% whether their are equal or not.

% If equal then, the result will be 1 (true); otherwise, 0 (false)

(NRow(1:k-1) == NCol(k))

% Step 3. Elementwise computation of the comparisons from Step 1 and Step 2

% simultaneously.

(NCol(1:k-1) == NRow(k)) .*(NRow(1:k-1) == NCol(k))

% Finally, the computation results from the two logical vectors from Step 1 and 2 are there

Walter Roberson
on 21 Oct 2021

The 1:k-1 can only work properly if k is a scalar.

NRow(1:k-1) == NCol(k)

That part tests whether each value in NRow before index k, is equal to the NCol entry at index k. The result is a logical vector of length k-1 . For example if k were 4, then NCol(4) is 2, and you would be testing NRow(1:3) == 2 which would give you the logical vector [false, false, true]

(NCol(1:k-1) == NRow(k))

That part tests whether each value in NCol before index k, is equal to the NRow entry at index k. The result is a logical vector of length k-1 . For example if k were 4, then NRow(4) is 2, and you would be testing NCol(1:3) == 2 which would give you the logical vector [false, false, false]

So you have two logical vectors of length k-1 and the .* multiplies the corresponding entries. Multiplication of corresponding logical values is the same as "and" of the entries.

The code could have been written as

c=(NCol(1:k-1) == NRow(k)) & (NRow(1:k-1) == NCol(k))

and the only difference would have been as to whether c would end up being a double precision vector (original code) or a logical vector (suggested code)

##### 3 Comments

De Silva
on 24 Oct 2021

### See Also

### Categories

### Community Treasure Hunt

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

Start Hunting!