Pick a value from a text
1 view (last 30 days)
Show older comments
Hello,
Just wanted to ask if there is a function which can pick a value from a large text of numbers and if it could pick say like every second number from the text as well? They are just random numbers in a text, I know there is the 'find' function but that only displays the position of the number. Thanks!
Regards, Steve
0 Comments
Accepted Answer
Star Strider
on 3 May 2015
To pick every second number from your vector V that is N-elements long, the easiest way would be to use the colon operator to generate a vector of indices:
V_result = V(1:2:N); % Start At 1 = 1,3,5,...
V_result = V(2:2:N); % Start AT 2 = 2,4,6,...
You can also use ‘logical indexing’, depending on how you want to address your vector. To use random integers to generate the index vectors, use functions such as randi and randperm.
For a matrix, this gets a bit more complicated, but is still not difficult.
2 Comments
Star Strider
on 3 May 2015
My pleasure!
In a matrix, you have two index vectors, one spanning the rows, and the other spanning the columns. So if we have the matrix magic(6) and we want the element in the third row and fourth column, one possibility would be:
M = magic(6)
M34 = M(3,4)
produces:
M34 =
22
Note that the indices have to be within the size limits of the matrix, but they can be identical, so M(2,2) is permitted.
Alternate index inquiries into the matrix would be:
M = magic(6)
N = length(M);
Modd = M(1:2:N, 1:2:N)
Meven = M(2:2:N, 2:2:N)
and would produce:
Modd =
35 6 19
31 2 27
30 34 14
Meven =
32 21 25
28 17 15
36 13 11
Experiment with it. The worst that can occur is that you have to use Task Manager (PCs) to close MATLAB if it takes more than a few minutes to run your code, if you‘re the impatient sort. Otherwise, just wait for it to finish.
And Monday, May the Fourth Be with 'you!
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!