How can i display this user defined matrix made with a loop
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
I used a loop to create a user defined matrix and i want to display in column form not row form. I can not get the code to fprintf in column form, any help would be greatly appreciated.
n = input('Enter your number of rows: ');
m = input('Enter your number of columns: ');
fprintf('Select a function:\n');
fprintf('1) Add\n');
fprintf('2) Subtract\n');
fprintf('3) Multiply\n');
fprintf('4) Divide\n');
fun_choice = input('Enter your choice (1:4): ');
% Calculation section:
matrix = zeros(n, m);
for k = 1:n
for h = 1:m
if fun_choice == 1
matrix(k, h) = k + h;
elseif fun_choice == 2
matrix(k, h) = k - h;
elseif fun_choice == 3
matrix(k, h) = k * h;
elseif fun_choice == 4
matrix(k, h) = k / h;
end
end
end
2 Kommentare
Dyuman Joshi
am 18 Apr. 2023
Say n=4, m=5 and fun_choice is 1. What is the output you want?
n=4;m=5;
matrix = zeros(n, m);
fun_choice = 1;
for k = 1:n
for h = 1:m
if fun_choice == 1
matrix(k, h) = k + h;
elseif fun_choice == 2
matrix(k, h) = k - h;
elseif fun_choice == 3
matrix(k, h) = k * h;
elseif fun_choice == 4
matrix(k, h) = k / h;
end
end
end
matrix
Antworten (2)
KSSV
am 18 Apr. 2023
n=4;m=5;
matrix = zeros(n, m);
fun_choice = 1;
for k = 1:n
for h = 1:m
if fun_choice == 1
matrix(k, h) = k + h;
elseif fun_choice == 2
matrix(k, h) = k - h;
elseif fun_choice == 3
matrix(k, h) = k * h;
elseif fun_choice == 4
matrix(k, h) = k / h;
end
end
end
fprintf('%f\n',matrix(:)) % print as column using fprintf
matrix(:)
fprintf('%f %f %f %f\n',matrix) % print like matrix using fprintf
matrix
0 Kommentare
Walter Roberson
am 18 Apr. 2023
My suspicion is that you have a situation something like
M = magic(4)
fprintf('%d %d %d %d\n', M)
and you are noticing that the output rows such as 16 5 9 4 do not correspond to the rows of the data, like 16 2 3 13
If so, there are two ways to proceed:
First you can do
fprintf('%d %d %d %d\n', M.')
The number of %d should be the same as the number of columns of data.
Or, you can use
compose("%d %d %d %d", M)
Or you can combine
fprintf('%s\n', compose("%d %d %d %d", M)) %format is used once per entry in the string array
or
fprintf('%s\n', join(compose("%d %d %d %d", M),newline)) %format is used once
0 Kommentare
Siehe auch
Kategorien
Mehr zu Variables finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!