a 1d array of even numbers between 1 and endvalue from smallest number to largest number in matlab

To create a 1D array of even numbers between 1 and a given endvalue in Matlab, you can use the mod function in combination with a loop. Here's an example code snippet that achieves this:

main.m
endvalue = 20;   % replace with your desired end value
even_numbers = [];   % initialize an empty array

for i = 1:endvalue
    if mod(i, 2) == 0
        even_numbers = [even_numbers i];
    end
end

disp(even_numbers);
220 chars
11 lines

This code snippet initializes an empty array even_numbers and then iterates through numbers from 1 to endvalue. The mod(i, 2) == 0 condition checks if the number i is even. If it is, the number i is added to the even_numbers array using the square brackets notation [even_numbers i]. Finally, the even_numbers array is displayed.

For endvalue = 20, the output will be:

main.m
2    4    6    8   10   12   14   16   18   20
47 chars
2 lines

This code can be easily modified to suit your specific needs by changing the value of endvalue.

Note: If you want the array to be sorted from smallest to largest, you can add the sort function before displaying the even_numbers array:

main.m
disp(sort(even_numbers));
26 chars
2 lines

This will sort the array in ascending order before displaying it.

related categories

gistlibby LogSnag