How do I use fprintf to print a matrix of MxM size where User chooses M

5 views (last 30 days)
If user chooses M which is the size of the matrix and it is a MxM size. How would I fprintf that if M could be any real number?
I posted a simplified version of my code because its for a college assignment and I dont want to get expelled.
% -------------------------------------------------------------------- %
clear;clc;
sized = input('Enter value for matrix size (will be square ie. 2x2, 3x3 etc). ');
randommatrix = rand(sized:sized)
randommatrix = round(randommatrix)
% I need to display the completed matrix to the command window
% this is what I have so far
fprintf('%d\n',' Final Matrix: ',randommatrix)
  1 Comment
Stephen23
Stephen23 on 6 Sep 2020
Edited: Stephen23 on 6 Sep 2020
Some comments:
  • note that sized:sized is just a more complex way of writing sized.
  • using the colon operator to specify the size of the matrix is playing with fire (or more precisely, memory errors). Avoid.
  • specifying the fprintf format as integer and then providing a character vector input is unlikely to do what you want (it will print the character values). To print a character vector/string you would need to use an appropriate format specifier, e.g. '%s'. In this case it is probably easier in a separate fprintf call.

Sign in to comment.

Accepted Answer

Stephen23
Stephen23 on 6 Sep 2020
>> N = 4;
>> M = randi([0,1],N,N);
>> F = [repmat(' %d',1,N),'\n'];
>> fprintf(F,M.')
1 0 1 1
1 1 1 1
0 1 1 0
1 0 1 1

More Answers (0)

Categories

Find more on Performance and Memory in Help Center and File Exchange

Products


Release

R2019a

Community Treasure Hunt

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

Start Hunting!