Thread Subject: Inverse of an array

Subject: Inverse of an array

From: Frank

Date: 23 Nov, 2009 21:07:19

Message: 1 of 3

I need to make a function that inverses an array by using a loop
so the function will for example inverse [1 2 3 4] into [4 3 2 1])
What's the easiest way to make this one?

Subject: Inverse of an array

From: Nathan

Date: 23 Nov, 2009 21:13:46

Message: 2 of 3

On Nov 23, 1:07 pm, "Frank " <frankie_1_9_...@hotmail.com> wrote:
> I need to make a function that inverses an array by using a loop
> so the function will for example inverse [1 2 3 4] into [4 3 2 1])
> What's the easiest way to make this one?

Here's a very simple loop.
A = [1 2 3 4];
for i=1
B = fliplr(A);
end
%%%%%%
B =
     4 3 2 1

A real example:

A = [1 2 3 4];
for i=1:length(A)
B(i) = A(length(A)-i+1)
end

or just a vectorized version (without using fliplr)
B = A(length(A)-A+1)

-Nathan

Subject: Inverse of an array

From: ImageAnalyst

Date: 23 Nov, 2009 21:23:37

Message: 3 of 3

The simplest "non-loop" version is this:

A = A(end:-1:1)

It's a neat trick that inside the (), MATLAB knows that the "end"
keyword means "length of the vector."

By the way, I'd call it "reverse" the vector, or "flip" it since, you
should recall, "inverse" has quite another meaning.

Tags for this Thread

Add a New Tag:

Separated by commas
Ex.: root locus, bode

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

rssFeed for this Thread

Contact us at files@mathworks.com