Inserting number where vector changes from positive to negative

3 views (last 30 days)
Hello,
I have searched related questions on the Matlab forum, but have not been able to find any useful documentation or help. So I am asking my question on this forum.
I am trying to insert two numbers into two different vectors. For the first case, I am trying to insert 0 (y_input) in the location between sign change (negative to positive) in my y vector. For the second case, I am trying to insert a specific number (x_input) in my x vector that corresponds to the same location as the 0 position in the y vector.
Any help to develop code that is able to find the sign change in the y vector and then insert a number in the y vector and have another number inserted in the y vector with the same position would be appreciated.
% this is rude to somebody else's environment if they want to copy and paste your code...dpb
%clear all; close all; clc
x = [-1 1 2 3 4];
y = [-1 1 2 3 4];
x_input = 0.05;
y_input = 0;
  3 Comments
KH
KH on 9 Jul 2019
Hi dpb,
I see that you have edited my original question in this forum. Is it not appropriate to provide code? I added the above code as a visual example to my text, since I am a visual learner and thought it would help those who also learn this way. Please help me understand why this is not appropriate.
dpb
dpb on 9 Jul 2019
Edited: dpb on 9 Jul 2019
The code is fully appropriate and appreciated -- I commented out the one line that, if a volunteer has a working environment going on his machine and pastes in your original code to the command window, and accidentally hits "Enter" before deleting the first line, then POOF!!! several hours of work may just disappear.
I know many instructors teach doing the above in MATLAB classes so that all homework assignments start from a clean slate, but in actual use, it's rarely needed and, as noted above, sometimes very costly.
So, I both applaud the posting and encourage you to continue to post the pertinent snippets of code just sans the "clear all" preamble...most all respondents here are active workers/researchers/engineers/whatevers with Matlab as their primary toolset so there's no telling what they've had going when taking a break to check Answers for a minute...
That aside, did the crystal ball come close to the desired result? <VBG>

Sign in to comment.

Answers (1)

dpb
dpb on 8 Jul 2019
On the chance the crystal ball foresaw the answer to the above questions, try the following (or perturbations thereof)...
x = [-1 1 2 3 4];
x_input = 0.05;
ip=find([0 diff(sign(x))]==2);
x=[x(1:ip-1) y_input x(ip:end)]
results in
>> x =
-1 0 1 2 3 4
>>

Categories

Find more on Graphics Object Programming 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!