How to solve these two problems in Matlab?
显示 更早的评论
- 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 个评论
Azzi Abdelmalek
2013-10-20
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.
采纳的回答
更多回答(1 个)
Image Analyst
2013-10-20
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.
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!