How to access alternate elements from a matrrix?

4 Ansichten (letzte 30 Tage)
Rohit Raut
Rohit Raut am 11 Apr. 2021
Kommentiert: Rohit Raut am 11 Apr. 2021
I have a matrix
a =
0 4 5 6 7 .... n
0 0 0 0 0 .....n
I want to access values 0, 5, 7 and do the operation 5-0, 7-5 and so on
Program I have is as follows:
clc
clear
n=input('Enter the number of elements: ');
for i=1:(2*n)+1
x(i)=input('Enter x coordinate of the node');
y(i)=input('Enter y coordinate of the node');
end
a=[x;y]
for i=1:2:n
L(i)=a(1,i+2)-a(1,i);
end
L
I am not getting the desired output. What am Idoing wrong?

Akzeptierte Antwort

Jan
Jan am 11 Apr. 2021
Bearbeitet: Jan am 11 Apr. 2021
a = [0 4 5 6 7; ...
0 0 0 0 0]
n = size(a, 2);
for i = 1:n / 2
k = (i - 1) * 2 + 1;
L(i) = a(1, k + 2) - a(1, k);
end
Easier:
L = diff(a(1, 1:2:end))

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Produkte

Community Treasure Hunt

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

Start Hunting!

Translated by