Can one have a function that opens and manipulates more than one file with name containing an array

1 回表示 (過去 30 日間)
If in a script named Overall I have :
angle = input('Which angles (degree) are you targeting: ')
>> [8 7 6 5 4 3 2 1]
followed by calling function:
Tablefliptrial(angle) %line 5
and then a create a separate .m file containing the function
function [desiredOutput] = tablefliptrial(angle)
fileID = fopen('distance',angle,'zenith.plt'); %open file %line 2
%do a bunch of operations towards desired output
desiredOutput = [] %huge matrix
end
Am I allowed to place the value of each angle so that the function reads each file format (i.e. distance1zenith, distance2zenith...) or do I need a different approach? Error given:
Error using fopen
Invalid permission.
Error in Tablefliptrial (line 2)
fileID = fopen('distance',angle,'zenith.plt'); %open file
Error in Overall (line 5)
Tablefliptrial(angle)

採用された回答

Ameer Hamza
Ameer Hamza 2018 年 5 月 29 日
編集済み: Ameer Hamza 2018 年 5 月 29 日
fopen() can only accept two inputs. The first input is filename and second is the permission. What you are doing, is to give 3 inputs to fopen(). Therefore fopen() is not working. Also each call to fopen() can only open 1 file so you will need to for loop. You need to do it like this
function [desiredOutput] = tablefliptrial(angle)
for i=angles
fileID = fopen(['distance',num2str(i),'zenith.plt']); %open file %line 2
%do a bunch of operations towards desired output
desiredOutput = [] %huge matrix
end
end
note that adding [] have converted the three inputs into one char array of the filename. You can specify the second input to fopen() as permission with which you want to open the file.
  4 件のコメント
fernando aguirre
fernando aguirre 2018 年 5 月 30 日
Thank you, got it all figured out!
Stephen23
Stephen23 2018 年 5 月 30 日
編集済み: Stephen23 2018 年 5 月 30 日
Always fclose every file that you fopen in the loop!
It is an very bad practice to leave files open like that: continually opening files can eventually cause MATLAB to crash. The MATLAB documentation specifically advises "When you finish processing the file, close it with fclose(fid).".
Always fclose after processing the files!

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

その他の回答 (1 件)

Walter Roberson
Walter Roberson 2018 年 5 月 29 日
Use sprintf or num2str to construct the file name.
  1 件のコメント
fernando aguirre
fernando aguirre 2018 年 5 月 29 日
So I changed Overall.m to be
angle = input('Which angles (degree) are you targeting: ');
anginput = num2str(angle);
Tablefliptrial(anginput);
but I am still received with invalid permission

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

カテゴリ

Help Center および File ExchangeFile Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by