Output Matrix in For Loop duplicates. Why?
Show older comments
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?
Answers (1)
KALYAN ACHARJYA
on 15 Oct 2018
Edited: KALYAN ACHARJYA
on 16 Oct 2018
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 Comments
KALYAN ACHARJYA
on 16 Oct 2018
Edited: KALYAN ACHARJYA
on 16 Oct 2018
sum1=[sum1];
disp(sum1);
Walter Roberson
on 16 Oct 2018
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.
KALYAN ACHARJYA
on 16 Oct 2018
Edited: KALYAN ACHARJYA
on 16 Oct 2018
@Walter Sir Thanks #Gratitude
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!