How to solve these two problems in Matlab?
Ältere Kommentare anzeigen
- Ask the user for an integer, m. Then use a for loop to create a row array with m elements consisting of all the integers from 1 to m. Use disp to display the resulting array. For m use 15.
- Use a for loop to extract every third element from the array created in previous problem and store the results in a new array. Use disp to display the resulting array.
I solve problem 1 as
for k=1:1
m=input('Enter a number of element, m\n');
array=[1:1:m];
disp (array)
end
But it makes the second problem no sense at all.
1 Kommentar
Azzi Abdelmalek
am 20 Okt. 2013
This is a homework, I advise you to read more about array, you can find in the net many tutorials about arrays, read also the help in Matlab.
Akzeptierte Antwort
Weitere Antworten (1)
Image Analyst
am 20 Okt. 2013
I'd do it this way:
% Ask user for a number.
defaultValue = 15;
titleBar = 'Enter m ';
userPrompt = 'Enter m';
caUserInput = inputdlg(userPrompt, titleBar, 1, {num2str(defaultValue)});
if isempty(caUserInput),return,end; % Bail out if they clicked Cancel.
m = round(str2double(cell2mat(caUserInput)));
% Check for a valid integer.
if isnan(m)
% They didn't enter a number.
% They clicked Cancel, or entered a character, symbols, or something else not allowed.
m = defaultValue;
message = sprintf('I said it had to be an integer.\nI will use %d and continue.', m);
uiwait(warndlg(message));
end
% Assign the array.
array1 = 1:m;
disp(array1);
% Vectorized way to extract every third element
array2 = array1(1:3:end)
% for loop method (might be slower for large arrays).
counter = 1;
for k = 1 : 3 : length(array1)
array3(counter) = array1(k);
counter = counter + 1;
end
disp(array3);
Note, I gave you both the for loop method and the vectorized method to extract every third element.
Kategorien
Mehr zu Loops and Conditional Statements finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!