====== MATLAB exercise solutions (Century College, CSCI 1081, Fall 2024) ====== a = [1 2 3 4 5 6]; %a = [1:6]; % also works disp(a * 7); % not provided. a = [2 3 1 5; 1 0 3 1; 0 2 -3 2; 0 2 3 1]; % either works for multiplying a matrix with a scalar: disp(a * 7); disp(a .* 7); a = [2 3 1 5; 1 0 3 1; 0 2 -3 2; 0 2 3 1]; b = inv(a); disp(a * b); % result is (approx.) identity matrix a = [2 3 1 5; 1 0 3 1; 0 2 -3 2; 0 2 3 1]; b = [1 2 3; 10 20 30; 0.1 0.2 0.3]; matrixinfo(a); matrixinfo(b); % square matrix of Inf values function matrixinfo(m) % matrix_info(m) % Tell the user whether mtx is a square matrix. If it is a square matrix, % display the matrix's transpose and inverse. msize = size(m); if ndims(m) == 2 && msize(1) == msize(2), disp('It''s a square matrix.'); disp('The transpose is:'); disp(m'); disp('The inverse is:'); disp(inv(m)); else disp('The matrix isn''t square.'); end % if end % function % Input data for three monkeys NUM_MONKEYS = 3; NUM_DAYS = 5; % initialize data to -1) data = ones(NUM_MONKEYS, NUM_MONKEYS) * -1; % Get monkey data for monkey = 1:NUM_MONKEYS, disp('----------'); % enter row data as days of week for day = 1:NUM_DAYS, is_valid = false; while ~is_valid, prompt = ['Monkey ' num2str(monkey) ', day ' num2str(day) ': ']; data(monkey, day) = input(prompt); is_valid = data(monkey, day) >= 0; if ~is_valid, disp('Try again.'); end; % if end % while end % inner for end % outer for % for each column, compute the average: avgeaten = zeros(1, NUM_DAYS); for day = 1:NUM_DAYS, avgeaten(day) = mean(data(:, day)); end % for % Display report disp('====================================='); disp('The average amount eaten on each day:'); disp(avgeaten); disp(['The least amount eaten this week: ' num2str(min(min(data))) ]); disp(['The greatest amount eaten this week: ' num2str(max(max(data))) ]); disp('=====================================');