How can i display this user defined matrix made with a loop
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
Dyuman Joshi
2023-4-18
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
回答(2 个)
KSSV
2023-4-18
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 个评论
Walter Roberson
2023-4-18
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 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!