I need the vectorize code a) vectorize your code and thus the function should ha
ID: 3719204 • Letter: I
Question
I need the vectorize code
a) vectorize your code and thus the function should have a single line of code besides the function heading and
end lines and comment line.
This is the none vectorized code:
M=[3 6 9; 12 15 18; 21 24 27]; %Matrix Declaration
max=18; %MaxValue
[rows, cols] = size(M); %to givem the size of the matrix in FILAS,COLUMNAS
sum_neg_max = 0; %Acumulador
%****NESTED LOOP****
for i = 1 : rows
for j = 1 : cols
if M(i, j) > max
M(i, j) = M(i, j) * -1;
end
sum_neg_max = sum_neg_max + M(i, j);
end
end
%**** Showing Results and Variables***
M
max
sum_neg_max
Explanation / Answer
-------------------------sumneg.m---------------------
function [sumnegmax] = sumneg(M , max_val)
sumnegmax = 0;
% get the dimensions of M
[r , c] = size(M);
for i = 1 : r
for j = 1 : c
% if current elements is greater than max
if M(i , j) > max_val
% negate the sign
M(i , j) = -M(i, j);
end
end
end
% calculate the sum of all elements
for i = 1 : r
for j = 1 : c
sumnegmax = sumnegmax + M(i , j);
end
end
end
-----------------------main.m---------------------
M=[3 6 9; 12 15 18; 21 24 27];
max_val = 14;
sumnegmax = sumneg(M , max_val);
M
max_val
sumnegmax
Sample Output
M =
3 6 9
12 15 18
21 24 27
max_val =
14
sumnegmax =
-75
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.