Problem when Indexing large integer arrays
3 views (last 30 days)
Show older comments
I created following code that is suposed to reverse a vector with huge length, in the order of hundreds of thousands:
function y=reversal(v)
n=25000;
if length(v)<n
y=[v(end):-1:v(1)];
else
y=[v(end:-1:(end-n)), reversal(v(1:end-n-1))];
end
end
The code is supposed to be recursive but supposed to split the input vector, since one million of single recursions will cause a memory error. With the default input, all the integers from 1 to 1 million it worked (v=(1:1e6)). With random integer array inputs the code fails in the size of the output array. I understand how that happens, if I split the input vector, for instance randi(1000,1,700725), the code will fail by the size of the output vector. Moreover, everytime I run the code with the same input vector (in terms of size and content, the size of reversed vector will also change.
I don't understand how the size of the reversed vector changes every time and how the way I split input vectors works for (1:1e6) , (1:999999) but not for the large integer vectors.
If anyone can give me an explanation for that I will be very grateful.
0 Comments
Accepted Answer
James Tursa
on 18 Dec 2020
Edited: James Tursa
on 18 Dec 2020
This
[v(end):-1:v(1)]
creates an indexing array that starts at the value v(end), increments by -1, and ends with v(1). It does not reverse the vector. To reverse the vector you need to have all the indexing inside the parentheses. E.g.,
v(end:-1:1)
E.g., if you had the following
v = [3 5 1 4 2]
then this code
[v(end):-1:v(1)]
would produce this result
2:-1:3
which would be empty.
But this code
v(end:-1:1)
would produce
[2 4 1 5 3]
If you fix your coding you will probably find that you don't need recursion for this.
0 Comments
More Answers (2)
Steven Lord
on 19 Dec 2020
If you call flip, fliplr, or flipud as appropriate you don't need to do the indexing yourself.
But since this is almost certainly homework, I'm guessing your professor forbade you from using those functions.
If you want to try to puzzle this out, think about breaking a smaller vector into smaller chunks.
x = 1:7
n = 3
If I told you to apply this technique to the x and n above can you write out the steps that you should follow with pencil and paper? If so can you then figure out how to convert those manual steps into code?
0 Comments
See Also
Categories
Find more on Creating and Concatenating Matrices 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!