Skip to content

Instantly share code, notes, and snippets.

@srishtis
Created August 26, 2018 09:53
Show Gist options
  • Save srishtis/11ca1e17ef6458c7f227440c2d94b12b to your computer and use it in GitHub Desktop.
Save srishtis/11ca1e17ef6458c7f227440c2d94b12b to your computer and use it in GitHub Desktop.
This is the code to raise each element of a matrix by its position index.
%simple/ easy-to-understand solution
function ans = matrix_pow(a)
append=[]
for i=1:numel(a)
addi= a(i)^i
append= [append addi]
end
sum(append)
end
%alternative and more efficient solution
function ans = matrix_pow(x)
%numel indicates the number of elements in an array or a matrix
%power command raises the power of the argument by the specified number (here 1:numel(x))
sum(power(x(:)',1:numel(x)));
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment