How do I make my script / function actually do something?

2 ビュー (過去 30 日間)
Nastassja Riemermann
Nastassja Riemermann 2019 年 3 月 25 日
回答済み: Nastassja Riemermann 2019 年 3 月 25 日
I'm running MATLAB R2018b - academic use, and am trying to run the following script saved in a file called problem0611.m. When I select "Run: problem0611", nothing prints to the command window, and nothing is saved to the workspace. I tried removing line 12 and just relying on the workspace, but even then nothing was saved to the workspace. How do I actually run this code? (I did do somet Googling to try to figure this out on my own, but didn't have any luck.)
function problem0611()
m=2;
n=3;
for i = 1:5
A = foo(m,n);
AAT = A*transpose(A);
ATA = transpose(A)*A;
rankAAT = rank(AAT);
detAAT = det(AAT);
rankATA = rank(ATA);
detATA = det(ATA);
A; AAT; rankAAT; detAAT; ATA; rankATA; detATA;
end
fprintf('\n');
end
function [myMatrix] = foo(m,n)
myMatrix = randi(7,m,n)-4*ones(m,n);
end

採用された回答

Walter Roberson
Walter Roberson 2019 年 3 月 25 日
Your code does not do any disp(), and has semi-colons at the end of each expression. The only output that you request is the fprintf() of a single newline.
The line
A; AAT; rankAAT; detAAT; ATA; rankATA; detATA;
is not a request to display or store the variables with those names. Instead each of those variables in turn is made the active variable (because their name is mentioned), and then the semi-colon right after says to discard the current expression, so nothing is displayed. If you were to change the semi-colon to comma then each of them would be displayed.
You are using a function. The variables you assign in the function are only active while the function is executing, and are discarded when the function returns. You do not return anything from the function, so as soon as preoblem0611 returns after executing, everything it built in the workspace will be discarded.
If you want to change something in the workspace that you run the function in, then you have to return the value from the function, and then when you call the function you would assign the value to the variable you want to save into. Your function foo is an example of doing just that.

その他の回答 (1 件)

Nastassja Riemermann
Nastassja Riemermann 2019 年 3 月 25 日
I changed line 12 to
A, AAT, rankAAT, detAAT, ATA, rankATA, detATA
and now I'm getting output. (I don't really need to save the variables to the workspace, as long as I have some way to view the results.) Thank you!

カテゴリ

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

Community Treasure Hunt

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

Start Hunting!

Translated by