How to get a vector using the following index. Please help me.

Hi guys, how to create the vector x = randperm(35)using only logical indexing:
y(x) = 2
if x < 6
y(x) = x - 4
if 6 <= x < 20
y(x) = 36 - x
if 20 <= x <= 35
where the curve should be a triangular shape, always above zero and with a maximum of 16. Im stuck with the my code where:
x=(1:35)
if(x<6)
y(x)=2
elseif(6<=x<20)
y(x)=x-4
elseif(20<=x<=35)
y(x)=36-x
end
plot(x,y)
But i cant seem to get a curve and get y to be right. is there a step where i missed?

2 Comments

p = randperm(n) returns a row vector containing a random permutation of the integers from 1 to n inclusive. In your case, randperm(35) "shuffles" integers from 1 to 35, so there must be some random number generation somewhere in your solution, .. or what did I misunderstand?
sorry about that, now that i looked at my question, i realized that i had a typo on randperm(35).

Sign in to comment.

 Accepted Answer

Well here's the code that will make the triangle, but I don't know what you're supposed to do after that to get a list of 35 numbers all scrambled up.
clc; % Clear the command window.
workspace; % Make sure the workspace panel is showing.
format long g;
format compact;
fontSize = 35;
% Make x and y;
x = 1:35;
y = 2 * ones(1, length(x)); % Preallocate.
logicalLeft = x < 6
logicalMiddle = x >= 6 & x <= 20
logicalRight = x >= 20
% Make the signal
y(logicalLeft) = 2; % Already 2 actually so does nothing.
y(logicalMiddle) = x(logicalMiddle) - 4;
y(logicalRight) = 36 - x(logicalRight);
plot(x, y, 'bo-', 'LineWidth', 2);
grid on;
xlabel('x', 'FontSize', fontSize);
ylabel('y', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Give a name to the title bar.
set(gcf,'name','Demo by ImageAnalyst','numbertitle','off')

3 Comments

Hi ImageAnalyst,
thanks for your answer, i was wondering why i cant use the if-else statement to get it work?
You can, but you'd have to put the if inside a for loop over all the x's.
for x = 1 : 35
if x >= ......etc.
oic, thanks for your help. i will take note next time.

Sign in to comment.

More Answers (0)

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!