given the row vector r = [1 2 6 -12 4 18 3 5 1 9]. using matlab conditional statements, create a new row vector that contain elements from row vector that are divisible by 3. in matlab

You can use a for loop with an if statement to accomplish this task. Here's the code below:

main.m
r = [1 2 6 -12 4 18 3 5 1 9]; % define the row vector
new_r = []; % create a new empty row vector

for i = 1:length(r) % iterate through each element of the row vector
    if mod(r(i),3) == 0 % check if element is divisible by 3
        new_r = [new_r r(i)]; % add element to the new row vector
    end
end

disp(new_r) % display the new row vector
349 chars
11 lines

Output:

main.m
6  -12  18  3  9
17 chars
2 lines

You can see that the new row vector only contains elements that are divisible by 3.

This code uses the mod() function to check if an element is divisible by 3. The mod() function returns the remainder when dividing the first argument by the second argument. So, if the remainder is 0, then the first argument is divisible by the second argument.

gistlibby LogSnag