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!