Run for loop and print data after each iteration
27 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
monkey_matlab
il 6 Ott 2015
Modificato: Kirby Fears
il 6 Ott 2015
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
clear;
clc;
[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;
else
v = vertcat(v,buffer);
end
i = i + 1;
end
% 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;
end
0 Commenti
Risposta accettata
Kirby Fears
il 6 Ott 2015
Modificato: Kirby Fears
il 6 Ott 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
eval(['volt_',num2str(ii)]);
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);
disp(printStr);
end,
Hope this helps.
1 Commento
Più risposte (0)
Vedere anche
Categorie
Scopri di più su Loops and Conditional Statements in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!