Output Matrix in For Loop duplicates. Why?

hi, I have a text file which I unpacked using importdata, and then quads.
M = importdata('Textfile.txt');
quads = M.data;
x = length(quads);
for i=1:x-1
quads(i)=quads(i+1)-quads(i);
P(i)= quads(i)/60;
end
the output is duplicated.
it will say
quads =
value
value
value
quads =
value
value
value
quads =
value
value
value
Is this because the TextFile.txt is a double array (as it says in Workspace) when I unpack it in Matlab?
----
A second question is I am trying to add up the differences in all the values and ultimately get the final value. How can I do this using a For Loop?
For ex; if the textfile contains
3
6
8
10
12
The differences between 3-0 = 3, 6-3 = 3, 8-6=2, and so forth..
3
3
2
2
2
Sum of all these = 12. The final value. What code can I add to my For Loop above?

回答(1 个)

In the second case, you can do this way
A=[3 6 8 10 12];
B=[0;A'];
sum1=0;
[rows colm]=size(B);
for i=1:rows-1
sum1=sum1+B(i+1,:)-B(i,:);
end
disp(sum1);
Command Window
>> 12
Recommended: There may another method to do the same without using a loop. (logical indexing)

4 个评论

Your command worked, thank you. How can i make it so that the output (12) is in a new matrix?
We recommend that you not use sum as the name of a variable. If you get in the habit of using sum as the name of a variable, it is pretty much inevitable that at some point in code after you have made sum into a variable, that you will try to invoke sum() as a function.
@Walter Sir Thanks #Gratitude

请先登录,再进行评论。

类别

帮助中心File Exchange 中查找有关 Loops and Conditional Statements 的更多信息

提问:

2018-10-15

Community Treasure Hunt

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

Start Hunting!

Translated by