For loop.how can I do it right?

1 回表示 (過去 30 日間)
Amjad AL Hasan
Amjad AL Hasan 2021 年 4 月 28 日
コメント済み: Amjad AL Hasan 2021 年 4 月 28 日
How can I do it right?
I am binger with MATLAB and I try to learn it. I have a data File with two columns ( x and y). The column x has content ages for the students and I should calculate the time between the ages using a "For" loop :
data=dlmread('volcanoes.dat')
x=data(:,2);
n=length(x);
for i=1:1:n
t(i)=x(i+1)-x(i)
end
plot(x,t,'bo');
but there's something wrong with my loop. I don’t know how to write it. How can I do it right?

採用された回答

Image Analyst
Image Analyst 2021 年 4 月 28 日
You can't go to n+1 when n is the last element of the vector. Try this:
data=dlmread('volcanoes.dat')
x=data(:,2);
n=length(x);
for i=1:n - 1
t(i)=x(i+1)-x(i)
end
plot(x, t, 'bo');
or better yet.
data = dlmread('volcanoes.dat');
x = data(:, 2);
t = diff(x); % Subtracts each element from the next one in the list.
plot(x(1:end-1), t , 'bo-', 'LineWidth', 2, 'MarkerSize', 16);
grid on;
xlabel('x', 'FontSize', 20);
ylabel('t', 'FontSize', 20);
  1 件のコメント
Amjad AL Hasan
Amjad AL Hasan 2021 年 4 月 28 日
Thank you very much, that was very helpfull.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeDownloads についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by