MATLAB: Does this question mean that I have to minus “1” from each element of matrix “A”? Any hint would help!

matrixmatrix manipulation

write a function that accepts in a matrix of any size(A) and outputs a matrix B such that on element-by -element basis? Then test it for any given matrix.
B(i,j,k,…)=A(i,j,k,…)+(i-1)+(j-1)+(k-1)…

Best Answer

That's fairly challenging compared to most homework problems we see. Since it needs to work with any number of dimensions, even up to a 20 dimensional matrix or more, I'd use linear indexing and ind2sub to get the i,j,k,etc. from the linear index. So start out something like this:
sizeA = size(A);
for linearIndex = 1 : numel(A)
indexes = .... some function to give you i,j,k,l,.... ind2sub() doesn't work.
for index = 1 : length(indexes)
thisIndex = indexes(linearIndex);
B(linearIndex) = A(linearIndex) + thisIndex - 1;
end
end
The tricky part is to get the "indexes" array. I thought ind2sub() would work but I couldn't get it to, unless I knew the number of outputs to expect in advance . In other words,
indexes = ind2sub(size(A), linearIndex);
surprisingly does not work to give you i,j,k,l,m,..... etc. (all as elements of a 1D array "indexes") unless you know in advance the last letter you'd need . At least I couldn't figure it out. So you might have to write that yourself.