Help with printing multiple variables in a single line with a loop?

조회 수: 7 (최근 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

채택된 답변

Image Analyst
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 CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by