필터 지우기
필터 지우기

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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by