If i have an array of four column and i want to write a program for the 3rd column like (x1^2-x2^2) + (x2^2-x3^2) + (x3^2-x4^2).....implies (square of 1st row, 3rd column- sq of 2nd row,3rd column) + ............

1 visualización (últimos 30 días)
I need to write a program that will automatically pick the relevant values turn by turn till it reaches the last value in the column and i don't need to write a long program list to compute. How do i do it?

Respuestas (1)

Gaurav Ahuja
Gaurav Ahuja el 9 de Jun. de 2017
it is unclear from the description the type of equation you would want to address in your program. But I think you are struggling with 'indexing of a matrix in MATLAB'. This can be understood by going through the following documentation link:
https://www.mathworks.com/company/newsletters/articles/matrix-indexing-in-matlab.html
to simplify this for you I will try to quantify few points that I think will help you make your own program.
to address an element i,j from the 2D array 'A', we execute A(i,j) where 'i' is the row and 'j' is the column. therefore, "square of 1st row, 3rd column" would mean square of A(1,3) and "square of 2nd row,3rd column" would mean square of A(2,3)
so you can execute the following A(1,3)^2 for finding the "square of 1st row, 3rd column"
in order to automatically pick the elements, we can iterate a variable in the row, and fix the column as 3. The following code will help you to relate it to your use case.
if true
% (x1^2-x2^2) + (x2^2-x3^2) + (x3^2-x4^2) for 3rd column
% let x = magic(4)
x = magic(10)
r = 10 % total number of rows
for i=1:r-3
y = (x(i,3).^2 - x(i+1,3).^2) + ...
(x(i+1,3).^2 - x(i+2,3).^2) + ...
(x(i+2,3).^2 - x(i+3,3).^2)
end
end

Categorías

Más información sobre Multidimensional Arrays en Help Center y File Exchange.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by