MATLAB Answers

Mat Lab Loop question It's not working properly. (Loops)

1 view (last 30 days)
John wick
John wick on 25 Aug 2019
Commented: John wick on 26 Aug 2019
Mat Lab question loop.jpg
I came up with this loop but it doesn't add up properly
x = randi(32,32,1);
for A = 1:32
disp(x(7+A))
end
or should it be like this?
x = 32;
y = rand(1,x);
z = 7:7:28;
for y(1,z) = y(1,z) + 7
fprintf('%d',y)
end

  0 Comments

Sign in to comment.

Accepted Answer

Rik
Rik on 25 Aug 2019
Neither, you need to tackle this problem step by step.
You need to create a random vector of integers. The second example doesn't return integers, while the first does. Since the excersize didn't specify any maximum value 32 should be fine. So x=randi(32,32,1); can stay.
Now to the loop. We need to look at every 7th element. There are two basic ways we can do that. We can either have some value and multiply it by 7, but in this case the other strategy is better: use the two-colon syntax to generate list of positions to change. You did that in your second code block when creating z.
Inside the loop we need to change a value. That mean we need to overwrite the value:
%set some value to var
var=3;
%increment var by 5:
var=var+5;
The doc of the for keyword provides some help how we can continue here: look at how you can change the first example to change a specific position in a vector, and the second example for how you can enter your own list of indices.
Nothing in the assignment says anything about displaying anything, so disp and fprintf are not needed.
If you need any more help, just write a comment.

  20 Comments

Rik
Rik on 26 Aug 2019
You're welcome. If my answer helped you, please consider marking it as accepted answer.
If your other questions are closely related to this one, feel free to post them in a comment here, otherwise it is probably better to post a separate question.
You can also have a read here to get some tips about how to find your own answers and how to write a good question. Also, your course instructor should be able to answer most of your questions. That might be a more efficient method to better understand how Matlab works.
Steven Lord
Steven Lord on 26 Aug 2019
In addition to what Rik said about asking your course instructor for help, if you haven't already done so I strongly encourage you to take the MATLAB Onramp training. It's free and it should help you develop a better understanding of how to work with MATLAB.
John wick
John wick on 26 Aug 2019
I have finished it around 80% it's a fun way to learn. After I finish I will redo it again!

Sign in to comment.

More Answers (0)

Sign in to answer this question.


Translated by