compute a scalar r that is the sum of the last 3 elements of matrix x in matlab in matlab

Assuming that you want to compute the sum of the last 3 elements of the matrix along the first non-singleton dimension, you can use the end keyword to index the last n elements of the matrix, where n corresponds to the dimension of the matrix. Here's an example:

main.m
x = [1 2 3 4 5; 6 7 8 9 10; 11 12 13 14 15]; % sample matrix
r = sum(x(end-2:end)); % compute sum of last 3 elements
117 chars
3 lines

In this example, x is a 3x5 matrix and r would be the sum of the elements 13, 14, and 15, which is 42.

Note that if x has only one dimension, you should use x(end-2:end) to compute the sum of the last 3 elements.

related categories

gistlibby LogSnag