Create a function file that will accept a 2-dimensional square (number of rows e
ID: 3552749 • Letter: C
Question
Create a function file that will accept a 2-dimensional square (number of rows equals the number of columns), determine the sum of the diagonal components of the 2-dimensional array starting in the upper left corner of the array and continuing through the lower right corner, and send back to the function call this sum. Your function may use either a for or a while loop to calculate the sum. Do not use any built-in functions other than size and/or length.
The sum would be 2 + 9 + 14 + 8 which is 33.
<?xml:namespace prefix = o /?>
Then create a script file that prompts the user to input a square 2-dimensional array. Call the function to sum the diagonal elements. You may assume that the user enters a square 2-dimensional array, you do not need to check that the entered array is square in either the function file or the script file.
Explanation / Answer
function [y]=arraysum(a)
[m n]=size(a);
sum=0;
for i=1:m
sum=sum+a(i,i);
end
y=sum;
end
---------------------------------------
the script:
-------------------------------------------------
a=input('enter a 2 dimensional array ');
b=arraysum(a)
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.