Create a simple table from using data from other table and an Iteration loop

Dear all,
I am very frustrated trying to create a very basic thing in Matlab for the past 4 hours with no success.
i have a table named time = [0;1;2;3;4;5;6;7;8;9;10;12;14;16;18;20;22;25;28;30];
I am trying to make a second table dt that will be the difference of the current minus the previous time.
dt = [1;1;1;1;1;1;1;1;1;1;1;2;2;2;2;2;2;3;2] using the following loop:
for i=2:20
k=time(i)-time(i-1);
dt(i-1)= k;
end
but I get the following error:
Subscripting a table using linear indexing (one subscript) or multidimensional indexing (three or more subscripts) is not supported. Use a row
subscript and a variable subscript.
Please help!!!
BR

댓글 수: 1

>> time = [0;1;2;3;4;5;6;7;8;9;10;12;14;16;18;20;22;25;28;30];
>> diff(time)
ans =
1
1
1
1
1
1
1
1
1
1
2
2
2
2
2
2
3
3
2

댓글을 달려면 로그인하십시오.

 채택된 답변

If you are really using the table datatype (as the error message suggests), then you are not indexing it properly. A table has variables, and you can index those as you are trying to do. So, I imagine you would need something like
for i=2:20
k=time.time(i)-time.time(i-1);
dt(i-1)= k;
end
It is a bit confusing to use 'time' as the name of both a table and a variable within that table, though you can do that if you want.
Looking at your code, though, I wonder why you need to use the table datatype at all. Why not just have a vector for time and a vector for dt?

댓글 수: 3

ok, and how would I go on doing that?
Pretty much like you already are doing it, but without the table datatype. For example,
clear all
time = [0;1;2;3;4;5;6;7;8;9;10;12;14;16;18;20;22;25;28;30];
dt = zeros(numel(time)-1,1);
for i=2:20
k=time(i)-time(i-1);
dt(i-1)= k;
end
Actually there is also a nice matlab function called 'diff' for successive differences, so you could just use that:
time = [0;1;2;3;4;5;6;7;8;9;10;12;14;16;18;20;22;25;28;30];
dt = diff(time);

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Logical에 대해 자세히 알아보기

제품

릴리스

R2019a

질문:

2019년 4월 28일

댓글:

2019년 4월 29일

Community Treasure Hunt

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

Start Hunting!

Translated by