How do you insert (not replace existing numbers) zeros in a column vector

I want to separate grouped variables in a plot by a space. In Excel you just add a blank column. In Matlab, do you just add zeros in the appropriate places in the column vector or can it be done in the plot function?
If you do just add zeros, how do you insert the zeros into the column vector thus increasing the size of the matrix from 9x1 to 11x1 in the following example? e.g.
>> A = [1 2 3 4 5 6 7 8 9]'
A =
1
2
3
4
5
6
7
8
9
>> A = [1 2 3 0 4 5 6 0 7 8 9]'
A =
1
2
3
0
4
5
6
0
7
8
9

1 Comment

How do you define where the zeros are inserted? Indices related to the original or to the new vector?

Sign in to comment.

 Accepted Answer

In Matlab, you put in nan or inf to cause that position to be skipped.

More Answers (1)

Following Walter's idea of the NaNs:
A = (1:9).';
% Build index
grp = 4; % Skip every 4 elements
numB = numel(A) + fix(9/grp); % Max elements including skips
idx = true(numB,1); % Preallocate true logical vector
idx(grp:grp:numB) = false; % Denote positions of skips
% Create new aray
B(idx) = A; % Assign values of A
B(~idx) = NaN; % Assign NaNs
% Plot segmented line
plot(B)

3 Comments

More common than the two logical indexing together would be:
B = nan(length(idx));
B(idx) = A;
I believe Jan indicated to me yesterday that using inf was faster than nan.
Yes, I recall that he said it many times on CSSM.
Me? During computations NaN's are much slower than "regular" doubles (x = rand(1e7, 1); tic; y=x+x; toc, x(:) = NaN; tic; y=x+x; toc). I've read that this concerns Intel processors, but AMDs should be able do add NaNs with the same speed (can anybody check this by a real test?). If SSE commands are used, the addition of NaN's and standard values has the same speed (in theory), therefore I assume e.g. SUM is not implemented in SSE.
BUT: *I* get the same speed for Inf's also, because they cause the same exceptions (usually). The creation of PLOTs seems to be faster with Inf's than with NaN's, but I do not any reason for this: Both are caught by mxIsFinite.
Conclusion: Test it in the individual case, if Inf or NaN is faster.

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!