General

Tech

Matlab assignment on for loopswhile loops

So this is my uni assignment
function [L, S, Lidx, Sidx] = largest_and_smallest(array)
%LARGEST_AND_SMALLEST Largest and smallest values in array
% [L, S, Lidx, Sidx] = LARGEST_AND_SMALLEST(ARRAY) returns
% the largest and smallest values in ARRAY, as well as the
% indices of the largest and smallest values.
% An error is raised if ARRAY is empty.

Basically, I have to find maximum, minimum value of an array using for loops/while loops and no max, min functions. I also need to find their index positions in the array.
I've tried to use for loops and
write something like for i=1:n and all that and then an if statement
if array(i)<=array(i+1)
L=array(i) etc
but I'm not getting it right.

Please help.

September 13, 2011

7 Comments • Newest first

Cawickeng

Yeah, I finished this last week and got full marks. I just came back to thank you guys. Turns out I had to put the initial condition of L=1 etc after the error function and use an else statement for that. Or something like that. But thanks guys. I think I might need help a few days later for another one, but only after I try it for myself (it's using Jacobi's method to find simultaneous eqns)

Reply September 23, 2011
BobR

What are you using as an "empty array"..?

Sleepydude's code will find an undimensioned array, that is an array with 0 elements in it, but it won't find an array that only contains zeros. (Like a 10 element array, all of which are zero.)

To find that you'd have to add a line between the last two "end" statements that says:

if S + L = 0
error('Array is empty')
end

This will detect all zeros in the array, if that's what you're looking for.

Reply September 15, 2011
Cawickeng

[quote=sleepyxdude]You can get the length of an array by just using the length function

N = length(array)

From there, I would check the empty array condition

if(N == 0)
error('Array is empty')

Getting the largest and smallest is pretty trivial. Just have to keep track of them in variables as you loop through each array element. I normally like to initialize everything to the first index. That way, you can skip 1 loop iteration to make it slightly more efficient

Lidx = 1
Sidx = 1
L = array(1)
S = array(1)

for i = 2:N
if (array(i) > L)
L = array(i)
Lidx = i
elseif (array(i) < S)
S = array(i)
Sidx = i
end
end[/quote]

Hmm, I just ran it and the only answer that's coming up is the max value. For some reason the other values aren't coming up. But thanks again for the help guys.
EDIT: The values are working correctly but the error isn't working for some reason.

Reply September 14, 2011 - edited
BobR

[quote=sleepyxdude]You can get the length of an array by just using the length function

N = length(array)[/quote]
Lol.. I knew there had to be a "magic bullet" I was missing.
Excellent..!

Reply September 14, 2011 - edited
BobR

Ok, I did some googling around and found the MatLab syntax and I see that it does need "end" statements after both "for" loops and "if" statements. That's easily fixed in that code.

It also looks like there's a way around having to know the maximum dimension of the array, by using error control statements.
As far as indexing arrays, try thinking of an apartment building, with 13 apartments in it (small building). There are 13 mailboxes in the lobby, one for each apartment.
The mailboxes are the array, the index to that array is the apartment number.

So, if you want to deliver mail to apartment 9, you'd put the mail into:

mailbox (9) == mail

And if the tenant in apartment 12 wants to get their mail they'd say:

mail == mailbox (12)

The index just "points" to an individual element in the array and lets you access the value that element holds. In a program, instead of a row of mailboxes there's a "row" of variables just like any other variable, but these are grouped together so you can work with any variable in the group just by using it's "index" number.

So in the function you need, the loop just looks at each variable in the array (each element) one by one by using "i" as the index and adding 1 to i each time through the loop. That way the index increases by one each time and looks at the value of the next element in the array each time through the loop.

You don't have to index an array sequentially, you can look at any element at any time, just like the mailboxes example above. That's what makes them so versatile, because you can access any of the variables in the array just by specifying one number.

BUT- if the mailman gets a letter addressed to "Apartment 15", there will be an error, because there IS NO mailbox number 15 in the mailbox array, so:

mailbox (15) == mail

will result in an "Index exceeds matrix dimensions" error, and the program stops.

So it's always important to know what the maximum dimension is, -OR- have a way to "trap" the error and continue.

This following code uses an error trapping statement I found in the MatLab documentation, but I don't know if you're supposed to use it yet or not (my teachers always got a little upset if I read ahead in the book and tried to use things that hadn't been introduced yet), but it should work.

i == 0 %this assumes the array starts at array(0)
L == 0
S== 0
%Initialize the index counter and variables. Don't know if that's needed in MatLab, but just in case, it can't hurt.

try

%this is the error control. It says try to execute the following statements and if there's no error, great. But if there IS an error, skip over everything in the program and %continue at the "catch" statement.
%This is what allows the program to end the while loop and continue, when all the elements of the array have been looked at and the index exceeds the maximum %dimension.

S == array(1)
%This sets the starting value of S to whatever is in the first element of the array. If there IS no element number 1, ie the array is empty, it will error and continue at the %"catch" statement further down.

while i > -1

% Run this loop as long as i is greater than -1. In this case, i will -always- be > -1, so this loop will essentially run forever until something breaks out of it.
%We expect that eventually the index will try to access an element of the array that is greater than the maximum dimension, and will cause an error, breaking the loop.

if array(i) > L
L=array(i)
Lidx = i
end

% If this current array element (the one indexed by i ) is larger than the biggest element found so far, then make L the value of this element, it's the largest found so far.
%Set the value of Lidx to the value of the index pointer, indicating the position of this element in the array.

if array(i) < S
S = array(i)
Sidx = i
end

%Same as above, but for the smallest value. S will be the smallest value found so far.

i == i + 1

%Increment the index counter for the next loop.

end

%This ends the "while" loop. The loop will continue back at the "while" statement and index (or look at) the next element in the array. This way it will step through the %array element by element comparing the value of each element to the Largest and Smallest found so far.

catch

%This is where the program will go when the value of i becomes bigger than the maximum dimension and causes the "Index exceeds matrix dimensions" error.
%Instead of stopping the program, the program will continue here.

if L + S = 0
... fprintf "Error, array is empty";

%If both L and S are zero, then the array must be empty.
%You'd have to put whatever you wanted the error to do in this part. (There is a minor consideration here which I'm going to ignore for the moment because it %complicates things a bit.)

%Also, I can't find anything that ends or returns from the function when it completes. I don't know if an "end" would be here, closing the function or not. Hopefully you'll
%know how to do that. At any rate, this should end the function. L will be the largest array element, S will be the smallest and Lidx and Sidx will contain the array index %for both the largest and smallest values.

I hope any of this makes any sense. And you have my deepest sympathies on having to work with MatLab, or math like this at all. Just looking at the matrix manipulations in the other sections of the documentation gave me a splitting headache.

Reply September 14, 2011 - edited
Cawickeng

Well the problem is that after the for loop you need an end function. Plus I'm kinda confused how to index the array. And no, this is a general function for any array, so we don't know the dimension of it. But thanks for the help. I'll try.
Hmm, just tried it, it doesn't work. I tested it on some random array where the last element is greater than the first element, so the function automatically states that the last element is the largest element of the array.

Reply September 14, 2011 - edited
BobR

I'm not entirely sure I'm fully understanding what exactly is needed, but this is my guess, with questions:

Do you know the number of elements in the array..?
I'm not familiar with MatLab, but with most languages you run into trouble if you try to access a higher number of elements than have been "dimensioned", or allocated, at the beginning of the program. That's usually an important thing to know when looping through an array so you don't go too high and exceed the maximum number of elements and cause an error.

Anyway, since I'm not familliar with the syntax of MatLab, this is how I'd do it, in a simplified "pseudo-code" that hopefully won't be too confusing:
(grr.. formatting is a problem too in this forum software. ... means tab, or space goes here.

L=0
S=0
%Initialize the Largest and Smallest variables

%I=Index Counter variable
%N=Maximum Number of array elements

FOR I=1 TO N

IF Array(I) > L
... L=Array(I)
... Lidx = I

% If this current array element is larger than the biggest element found so far, replace the value of L with the value of this element.
%Set the value of Lidx to the value of the index pointer, indicating the position of this element in the array

IF Array(I) < S
... S = Array(I)
... Sidx = I

%Same as above, but for the smallest value.

NEXT I

%Step through the entire array

IF L = 0 AND S = 0
PRINT "Error, Array is empty"

%Assuming the array is initialized to zero values, if you find the Largest and Smallest values in the array are zero, then the array must be empty.

END (or RETURN)

%Thas all folks

The problem with this is it sounds a lot simpler than what you were trying to describe, so I'm not sure if it's what you were getting at, but it would produce the largest and smallest values held in an array, along with their positions in the array.

Reply September 13, 2011 - edited