I am trying to create a nested loop from a random matrix and display the max value of each row and each column without using max function.

2 次查看(过去 30 天)
%it has to have user inputs for rows and columns, and a random generation of the matrix, which i have already. I am having problems getting the max value of each separate row and column, and it will not loop through each row and column.
rows=input('Enter the number of rows: '); cols=input('Enter the number of columns: '); rng('shuffle') matran=randi(100,rows,cols) maxrow=matran(1:1); maxcol=matran(1:1); for row = 1:rows if matran(row) > maxrow maxrow= matran (row);
end
for col = 1:cols
if matran(col)> maxcol
maxcol=matran(col);
end
end
end

回答(1 个)

BhaTTa
BhaTTa 2024-7-23
Here is the code to get max value from each row and column:
rows = input('Enter the number of rows: ');
cols = input('Enter the number of columns: ');
rng('shuffle');
matran = randi(100, rows, cols);
% Initialize arrays to store max values for each row and column
max_row_values = zeros(1, rows);
max_col_values = zeros(1, cols);
% Find max values for each row
for row = 1:rows
max_value = matran(row, 1);
for col = 1:cols
if matran(row, col) > max_value
max_value = matran(row, col);
end
end
max_row_values(row) = max_value;
end
% Find max values for each column
for col = 1:cols
max_value = matran(1, col);
for row = 1:rows
if matran(row, col) > max_value
max_value = matran(row, col);
end
end
max_col_values(col) = max_value;
end
disp('Matrix:');
disp(matran);
disp('Max values of each row:');
disp(max_row_values);
disp('Max values of each column:');
disp(max_col_values);

类别

Help CenterFile Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息

标签

Community Treasure Hunt

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

Start Hunting!

Translated by