Incremental indexing to create an array

9 views (last 30 days)
Hi,
I have a 1097x1097 array (called list_of_distances) and would like to index into that array repeatedly; I only need certain values from the array. By doing this repeated indexing, I'd like to create new array that is 1x1097 of values. I included a screen shot of the values I'm looking to get into a new array.
Any help would be appreciated
Michael
Michael
R = 2
S = 1
for i = length(list_of_distances)
final_list(i) = list_of_distances(R,S)
R = R+1
S = S+1
end

Accepted Answer

Peng Li
Peng Li on 15 Apr 2020
using diag(list_of_distances, -1) to get the diagonal you want.
  5 Comments
Peng Li
Peng Li on 15 Apr 2020
the loop doesn't run as your i is fixed at length(list_of_distances), and you prob want to do for i = 1:length(list_of_distances), but this way you are up to an indexing error as I commented above, you aren't able to have a vector of 1097 elements. Do for i = 1:size(list_of_distances, 1)-1 instead.
And you don't necessarily need to do a loop, although you are not familiar with some of these builtin functions. For this case, you can do list_of_distances(2:size(list_of_distances, 1)+1:end), which will give you the same results as diag(list_of_distances, -1).
list_of_distances = magic(10)
list_of_distances =
92 99 1 8 15 67 74 51 58 40
98 80 7 14 16 73 55 57 64 41
4 81 88 20 22 54 56 63 70 47
85 87 19 21 3 60 62 69 71 28
86 93 25 2 9 61 68 75 52 34
17 24 76 83 90 42 49 26 33 65
23 5 82 89 91 48 30 32 39 66
79 6 13 95 97 29 31 38 45 72
10 12 94 96 78 35 37 44 46 53
11 18 100 77 84 36 43 50 27 59
>> b = diag(list_of_distances, -1)
b =
98
81
19
2
90
48
31
44
27
>> c = list_of_distances(2:size(list_of_distances)+1:end)
c =
98 81 19 2 90 48 31 44 27
Michael King
Michael King on 15 Apr 2020
thanks, I've learned a lot here! much appreciated

Sign in to comment.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!