How do I replace a specific value in vector after its been through a loop?
12 views (last 30 days)
Show older comments
BRAWR is the sound that I make when I can't figure how this is supposed to work. For this assignment I'm meant to "declares a vector of numbers, A, and creates a new vector B, containing the cubes of the positive numbers in A. If an element is negative, put zero in the corresponding position in B. Your solution must use a loop to iterate through the vectors." however I can't make the corresponding position at b zero. heres what I have done so far.
A= [1, 2, -1, 5, 6, 7, -4, 3, -2, 0]; c=A for i=1:c if mod(c,2)==0 c=0 else c=c.*c.*c end end which gives me this c =
1 8 -1 125 216 343 -64 27 -8 0
0 Comments
Answers (1)
Adam
on 23 Mar 2016
Edited: Adam
on 23 Mar 2016
c = A;
will create an array c of length equal to A.
You don't then want to use
for i = 1:c
as a for loop condition as this doesn't make much sense. Seemingly it doesn't crash though I've never done it to know exactly what it will do.
i in your for loop is the index into the array so you should be doing something more like
c = zeros( size(A) );
for i = 1:numel(c)
if someCondition
c(i) = someValue
end
end
That is a general idea obviously, you have to fill in the relevant bits yourself.
I'm not sure why you are using 'c' when the questions asks for 'B', but that is a minor issue. Also I'm not sure what the question expects you to do with respect to initialisation of your B vector. If you initialise with zeros as I did then obviously you needn't do anything to explicitly put a zero in so I only included the clause for writing non-zero values.
This is a problem I would never use a for loop to solve in the first place so coursework insisting on you using a for loop is 'surprising' from a teaching perspective, but c'est la vie, that is what you are asked to do!
0 Comments
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!