Run for loop and print data after each iteration

82 views (last 30 days)
Hello, in my attached Matlab Code, I would like to run the for loop to carry out the calculation on each of the DataX and then print the result after each iteration. So after my first run of the for loop, the result should be: " At Freq 136, the sum of volt 1 = 55. Can you tell me what I am doing wrong? Here is my code:
% Select file
[FileName,PathName] = uigetfile('*.txt','Select data file');
fid = fopen( strcat(PathName,FileName) ,'rt' );
% Read the file and store into matrix v
i = 0;
v = [0 0];
while feof(fid) == 0
buffer = fscanf(fid, '%f', 5);
buffer = buffer';
if i == 0;
v = buffer;
v = vertcat(v,buffer);
i = i + 1;
% Frequency vector
freq = v(:,1);
% Data 1
Data1 = v(2:end,2);
Freq1 = v(1,2);
% Data 2
Data2 = v(2:end,3);
Freq2 = v(1,3);
% Data 3
Data3 = v(2:end,4);
Freq3 = v(1,4);
% Step 1-Convert y-data from power to volts
for ii = 1:3,
volt_ii = sqrt(10.^(Dataii./10));
summer_ii = sum(volt_ii);
printf('At Freq %d, the sum of volt %d = %d', Freqii, ii, summer_ii);
ii = +ii;

Accepted Answer

Kirby Fears
Kirby Fears on 6 Oct 2015
Edited: Kirby Fears on 6 Oct 2015
Hi monkey_matlab,
When you write "volt_ii" (or "Dataii") Matlab will not resolve it to volt_1 (or Data1). Matlab reads this as a variable literally named volt_ii which is the same on every iteration of your loop. If you want Matlab to resolve the name, you'd need to write something like
Realistically you don't need to use this approach at all. Everything after your while-loop can be done this way instead:
vFreq = v(1,2:4);
vData = v(2:end,2:4);
for ii=1:size(vData,2),
tempVolt = sqrt(10.^(vData(:,ii)./10));
tempSum = sum(tempVolt);
printStr=sprintf('At Freq %d, the sum of volt %d = %d',...
vFreq(ii), ii, tempSum);
Hope this helps.
  1 Comment
monkey_matlab on 6 Oct 2015
Edited: monkey_matlab on 6 Oct 2015
Exactly the output that I needed. THANK YOU!

Sign in to comment.

More Answers (0)


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!