MATLAB Answers


How does Matrix(300​2:2001:199​9998)=0.4 works?

Asked by WEI MA
on 19 Apr 2019
Latest activity Commented on by James Tursa
on 19 Apr 2019
I have a matrix with size of 1000*2000,
There is a line about : A(3002,2001,1999998) = 0.4 and the output looks like this
1.pngCan anyone help me to understand how this works?
Thanks in advance

  1 Comment

I'm assuming this expression in your question is a typo
and you really meant this based on your title

Sign in to comment.





3 Answers

Answer by madhan ravi
on 19 Apr 2019

Matrix = [1:3;4:6;7:9]
Matrix(1:2:end) = 0 % I suggest you to read about MATLAB indexing


Sign in to comment.

Answer by Andrei Bobrov
on 19 Apr 2019

[ii,jj] = ind2sub([1000,2000],3002:2001:1999998);
A = sparse(ii,jj,.4,1000,2000);


Sign in to comment.

Answer by Walter Roberson
on 19 Apr 2019

It is due to linear indexing. Variables can be indexed by a single number which is the number of elements from the beginning in continuous memory. Data is stored column by column (rows increase while column stays the same), so the first thing in memory is A(1,1), relative index 1, the second is A(2,1) relative index 2, then A(3,1) relative index 3, and so on, to A(1000,1) relative index 1000 . After that in memory is A(1,2), relative index 1001, then A(2,2) relative index 1002, A(3,2) relative index 1003, and so. 3000 would be the bottom of the third column, then 3001 would be the top of column #4, 3002 would be one entry down from that, at (4,2) .
Entries that are at the same row and adjacent columns are 1000 further on the location on the left (all in the case of 1000 rows that is). A difference of 2000 in memory would be same row, 2 columns earlier. 2001 further on from a location is therefore 2 columns to the right and 1 row down.. a chess move away. 2001 after that would be a further two columns to the right and another row down, and so on.


Sign in to comment.