Generate multiple matrices based on multiple inputs

조회 수: 3 (최근 30일)
Ashton Linney
Ashton Linney 2020년 4월 6일
댓글: Ashton Linney 2020년 4월 7일
I have this code that asks the user to input which type they would like to select out of 1 2 and 3. They can input multiple.
It currently works such that if they input a single type, a certain 4x16 matrix will be generated and then converted into four 4x4 matricies where the nth row of the 4x16 matrix corresponds to the nth matrix.
clearvars; close all
% User selects which type they would like.
prompt = 'Select which type(s) you would like: 1, 2 or 3. For multiple, seperate numbers with a space.';
type_string = inputdlg(prompt);
type = str2num(type_string{1})
% Based on the selected type, a 4 by 16 matrix is generated.
if type == 1
matrix = randi([0, 9], [4,16]);
disp('User has selected type 1.')
elseif type == 2
matrix = randi([10, 19], [4,16]);
disp('User has selected type 2.')
elseif type == 3
matrix = randi([20, 29], [4,16]);
disp('User has selected type 3.')
end
% Converts the 4x16 matrix into four 4x4 matrices, where the first row is converted into the first matrix ect.
MAT = zeros(4,4,4);
for k = 1:size(matrix,1)
vec = matrix(k,:);
MAT(:,:,k) = reshape(vec,[4,4]);
end
How can I make this code work using multiple if conditions so if multiple types are input, it will generate the specific multiple 4x16 matrices and then give the multiple sets of four 4x4 matrices?
Thank you

채택된 답변

Stephen23
Stephen23 2020년 4월 6일
편집: Stephen23 2020년 4월 6일
P = 'Select which type(s) you would like: 1, 2 or 3. For multiple, seperate numbers with a space.';
C = inputdlg(P);
V = sscanf(C{1},'%f'); % convert to numeric
R = {[0,9],[10,19],[20,29]};
F = @(x)randi(R{x},[4,16]);
M = arrayfun(F,V,'UniformOutput',false); % or use a loop.
fprintf('user selected type %u\n',V); % optional
It is not clear why you reshape after creating the matrices: why not just create them with the correct size in the first place?

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by