Help with printing multiple variables in a single line with a loop?
2 次查看(过去 30 天)
显示 更早的评论
I have to create a script that runs a loop over the values from N = 1 to N = 10 and outputs the magic sum. For N=2, the script should output a statement that states MATLAB does not output a valid magic square for N=2.
The output is supposed to look like this:
The magic sum for N=1 is 1 MATLAB does not output a valid 2x2 magic square The magic sum for N=3 is 15 The magic sum for N=4 is 34 The magic sum for N=5 is 65 The magic sum for N=6 is 111 The magic sum for N=7 is 175 The magic sum for N=8 is 260 The magic sum for N=9 is 369 The magic sum for N=10 is 505
This is what I have so far, but when I run it I get a completely bizarre, long output. I can't figure out how to print both the magic sum and the integer number (N) in the same line, I can only seem to do one or the other. I've been working on this for over four hours and can't seem to find a solution!
for N = 1:10,
MS = magic(N);
if (N==1) || (2<N) && (N<=10)
fprintf('The magic sum for N=%d', N, ' is %d', MS);
else
fprintf('MATLAB does not output a valid 2x2 magic square');
end
end
0 个评论
采纳的回答
Image Analyst
2018-8-24
Try this:
for N = 1:10
if N > 2
fprintf('\nMagic Square for N = %d\n', N);
MS = magic(N)
sumOfColumns = sum(MS, 1);
fprintf('The magic sum for N=%d is %d\n', N, sumOfColumns(1));
else
fprintf('MATLAB does not output a valid %d-by-%d magic square.\n', N, N);
end
end
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!