How can I read the elements of an array backwards?

I have an array with x = 250000 elements. I want the code to read backwards a part of it:
k = pks3(1):-1:1;
%read data points backwards starting from pks3 and ending at the beginning
So even though I have i = 10 pks3 peak points, I want to create an array k from the first point pks3(1). But, the problem is that in the end I get k = 255997855 elements, in which the pks3 point for example is repeated for several hundreds of times. The rest of the code is this:
k = pks3(1):-1:1;
%read data points backwards starting from pks3 ending to pks3 again.
first = k(k<xfb1); % find all k such that k is smaller than xfb1
if ~isempty(first)
first = first(1); %store the first number which is smaller than xfb1
else
disp('No value of k is smaller than xfb1.')
end
distQ = length(first:pks3(1));
Qstart = locs_RwaveB(1)*distQ; %distance from locs_RwaveB to Qstart point
What am I doing wrong?
Thanks.

 Accepted Answer

It appears to me that you are trying to do something very simple in a very convoluted way, probably due to programming practices in another language.
If you need to read x in reverse order, assuming x is a column vector simply do:
x = flipud(x); % flips the vector.
And now you can access it in forward order.

6 Comments

I used the fliplr function instead, since all elements are placed on one row, but there was no success.
Show a smaller concrete example with a ten element vector not a 250000 element vector.
theVector = sin(1:10)
What do you expect the result to be when you operate on that vector and how specifically did you obtain that result? Explain in words, if possible, not code.
It's difficult to explain with such a small vector since the data I have come from a digital signal, but let's say if I put a threshold on a vector sin(1:100), where 1 is on the bottom of the signal and 100 is on the peak, I want to put a threshold at i.e. 20 and tell the code to return the first point which is smaller than the threshold.
After the fliplr function, I wrote this line:
k = B(pks3(1):end);
and I get the error message:
Warning: Integer operands are required for colon operator when used as index
I understant that it might be due to the "end" I've inserted, but how else could I define the end of the vector? I tried the fix, ceil, floor and round functions, but I get the same error message.
The problem is not the end, it is the pks3(1). What value does pks3(1) have?
pks3(1) = 2.3937e+08

Sign in to comment.

More Answers (1)

Categories

Community Treasure Hunt

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

Start Hunting!