Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

MATLAB Help: Write a MATLAB program that will find the biggest number next to a

ID: 3725336 • Letter: M

Question

MATLAB Help:

Write a MATLAB program that will find the biggest number next to a zero. For example, given a vector VEC = [0 12 34 7 9 2 13 4 0 4 ], the biggest number next to a zero is 12, out of 12, 4 and 4. The program should generate a 1 by 10 vector consisting of random integers between 10 and 50, it will then randomly pick three elements of the vector and change their values to 0. Finally, it will find the biggest number that is next to a zero. Example shown below.

----------------------

The random vector VEC is [9 0 23 5 16 7 8 0 3 3 ]

The biggest number next to a zero is 23.

---------------------

Explanation / Answer

VEC = randi([10 50],1,10);

for i = 1:3
VEC(randi([1,10], 1, 1)) = 0;
end

max = 0;

for i = 1:10
if VEC(i) == 0 %number is zero check it's neighbours for a max number
if i>0 && VEC(i-1)>max%check left, make sure left exits
max = VEC(i-1);
end
if i<10 && VEC(i+1)>max%check right, make sure right exits
max = VEC(i+1);
end
end
end


str = num2str(VEC);
disp(sprintf('The random vector VEC is [%s]. The biggest number next to a zero is %d.', str, max))

%Hope this helps :)

Sample Output -

>> Untitled
The random vector VEC is [15 12 13 16 23 22 0 32 0 0]. The biggest number next to a zero is 32.
>> Untitled
The random vector VEC is [33 50 32 0 0 27 30 12 0 12]. The biggest number next to a zero is 32.
>> Untitled
The random vector VEC is [35 43 0 48 17 0 46 34 0 35]. The biggest number next to a zero is 48.
>>