Generate multiple matrices based on multiple inputs
11 次查看(过去 30 天)
显示 更早的评论
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
0 个评论
采纳的回答
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 Center 和 File Exchange 中查找有关 Resizing and Reshaping Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!