フィルターのクリア

How to make a text file from functions

3 ビュー (過去 30 日間)
Chloe
Chloe 2024 年 4 月 22 日
回答済み: Sanju 2024 年 4 月 29 日
x = 1
y = 1
myFile = fopen('myValues.txt', 'w')
fprintf(myFile, "X Length\tY Length\t Hypot Length\t\tPerimeter\t\tArea\n")
for i = 1:5
for j = 1:5
myHypot = hValue(i,j)
myPerim = pValue(i,j)
myArea = aValue(i,j)
fprintf(myFile, string(i) + "\t\t\t" + string(j) + "\t\t\t\t" + string(myHypot) + "\t\t\t" + string(myPerim) + "\t\t\t" + string(myArea) + "\n")
end
end
function hValue = hValue(xValue,yValue)
hValue = sqrt(xValue.^2+yValue.^2);
end
function pValue = pValue(xValue,yValue)
pValue = (xValue + yValue + (sqrt(xValue.^2+yValue.^2)));
end
function aValue = aValue(xValue,yValue)
aValue = 0.5*xValue*yValue;
end
  1 件のコメント
Walter Roberson
Walter Roberson 2024 年 4 月 22 日
Just remember to fclose(myFile) at the end.

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

回答 (1 件)

Sanju
Sanju 2024 年 4 月 29 日
Hi Chloe,
To generate a text file using MATLAB functions, utilize the "fprintf" function to input the desired content into the file. It appears that the code you've written is functioning correctly; however, remember to close the file once the operation is complete.
Here's the updated code,
x = 1;
y = 1;
myFile = fopen('myValues.txt', 'w');
fprintf(myFile, "X Length\tY Length\t Hypot Length\t\tPerimeter\t\tArea\n");
for i = 1:5
for j = 1:5
myHypot = hValue(i,j);
myPerim = pValue(i,j);
myArea = aValue(i,j);
fprintf(myFile, string(i) + "\t\t\t" + string(j) + "\t\t\t\t" + string(myHypot) + "\t\t\t" + string(myPerim) + "\t\t\t" + string(myArea) + "\n");
end
end
fclose(myFile);
function hValue = hValue(xValue,yValue)
hValue = sqrt(xValue.^2+yValue.^2);
end
function pValue = pValue(xValue,yValue)
pValue = (xValue + yValue + (sqrt(xValue.^2+yValue.^2)));
end
function aValue = aValue(xValue,yValue)
aValue = 0.5*xValue*yValue;
end
This code will create a file named "myValues.txt" and write the desired content to it. Each line in the file will contain the values of i, j, myHypot, myPerim, and myArea separated by tabs.
Hope this helps!

カテゴリ

Help Center および File ExchangeData Import and Analysis についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by