フィルターのクリア

Run for loop and print data after each iteration

27 ビュー (過去 30 日間)
monkey_matlab
monkey_matlab 2015 年 10 月 6 日
編集済み: Kirby Fears 2015 年 10 月 6 日
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

採用された回答

Kirby Fears
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.
  1 件のコメント
monkey_matlab
monkey_matlab 2015 年 10 月 6 日
編集済み: monkey_matlab 2015 年 10 月 6 日
Exactly the output that I needed. THANK YOU!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by