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

2 visualizaciones (últimos 30 días)

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

Respuesta aceptada

Image Analyst
Image Analyst el 24 de Ag. de 2018
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

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Community Treasure Hunt

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

Start Hunting!

Translated by