How to make a text file from functions

조회 수: 5 (최근 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 CenterFile Exchange에서 Biological and Health Sciences에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by