Mat Lab Loop question It's not working properly. (Loops)
1 view (last 30 days)
Show older comments
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
Accepted Answer
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
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.
More Answers (0)
See Also
Categories
Find more on Logical 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!