How to solve these two problems in Matlab?

  1. 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.
  2. 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 Comment

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.

Sign in to comment.

 Accepted Answer

Dear Kaimeng, here is code for this:
m = input('Input value for m:');
arr = zeros(1, m);
for i = 1:m
arr(i) = i;
end
disp(arr)
count = 1;
for i = 3:3:m
arr2(count) = arr(i);
count = count + 1;
end
disp(arr2)
I hope it helps. Good luck!

3 Comments

Can I solve problem 1 like this?
for k=1:1
m=input('Enter a number of element, m\n');
array=[1:1:m];
disp (array)
end
Yes you can but in that case for loop will be meaning less because you are using vector approach to fill the array and loop doing nothing interesting. Otherwise you can solve all the problem in vector for without for loop as below:
m = input('Input value for m:');
arr = 1:m;
disp(arr)
arr2 = arr(3:3:m);
disp(arr2)
So if you need to use for loop then try to use that you do something in it. It is more intuitive
What is the loop over k for? It only executes once. Also [1:1:m] can be more simply given as 1:m. And of course your input line is screwed up. See my answer.

Sign in to comment.

More Answers (1)

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.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!