Generate multiple matrices based on multiple inputs

3 vues (au cours des 30 derniers jours)
Ashton Linney
Ashton Linney le 6 Avr 2020
Commenté : Ashton Linney le 7 Avr 2020
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

Réponse acceptée

Stephen23
Stephen23 le 6 Avr 2020
Modifié(e) : Stephen23 le 6 Avr 2020
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?

Plus de réponses (0)

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Produits


Version

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by