Run for loop and print data after each iteration
22 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Kirby Fears
2015-10-6
编辑:Kirby Fears
2015-10-6
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.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!