Help with accessing variables outside a function

I am trying to create a function with two inputs: input_data(a,b). The input 'a' will indicate the sampling rate and input 'b' indicates the value. So if it was input_data(30,400), the data will be written to a text file with the value 400 from indexes 1-30. As an example:
1 400
2 400
3 400
4 400
. 400
. 400
. 400
How do i make the function so that everytime i call the function, it appends to the previous list in the text file? I want it to continue incrementing the index values from the previous entry. Thank you.

 채택된 답변

Bandar
Bandar 2014년 6월 2일
편집: Bandar 2014년 6월 3일

0 개 추천

This is my code for your question
function [] = input_data(a, b)
file = fopen('data.txt', 'a+'); % append data to an existing txt file (Note: 'a' for appending)
A = textread('data.txt');
if (isempty(A))
i = 1;
for i = i:1:a
fprintf( file, '%i %f ', i, b);
i = i + 1;
end
else
start = A( size(A,2) - 2) + 1;
for j = start:1:a+start-1
fprintf( file, ' %i %f ', j, b);
j = j + 1;
end
end
fclose(file);
end
in the main,
>> input_data(2, 400)
>> input_data(2, 400)
>> input_data(3, 300)
In the txt file
1 400.000000 2 400.000000 3 400.000000 4 400.000000 5 300.000000 6 300.000000 7 300.000000
Hope this helps.

댓글 수: 5

Victor
Victor 2014년 6월 2일
If i call the function again with a different a and b value, will the index continue incrementing from the previous value in the text file?
Bandar
Bandar 2014년 6월 3일
편집: Bandar 2014년 6월 3일
@Victor, I've updated the code. The answer for your comment is Yes. Mark it as solved if you think this works for you.
Victor
Victor 2014년 6월 3일
matlab is telling me to use textscan instead of textread. how do i implement this?
Victor
Victor 2014년 6월 3일
also, if i were to use more than 2 inputs lets say: input_data(a, b, c, d, e). Then the code does not work. 'a' would still indicate the index and 'b', 'c', 'd', 'e' would represent inputted constant values like "400."
Bandar
Bandar 2014년 6월 5일
I suggest you to make another question that suits your needs. The answer is for your first question.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

도움말 센터File Exchange에서 Matrix Indexing에 대해 자세히 알아보기

질문:

2014년 6월 2일

댓글:

2014년 6월 5일

Community Treasure Hunt

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

Start Hunting!

Translated by