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 个评论
Jan
2011-3-9
How do you define where the zeros are inserted? Indices related to the original or to the new vector?
采纳的回答
更多回答(1 个)
Oleg Komarov
2011-3-9
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 个评论
Walter Roberson
2011-3-9
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.
Oleg Komarov
2011-3-9
Yes, I recall that he said it many times on CSSM.
Jan
2011-3-9
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.
类别
在 帮助中心 和 File Exchange 中查找有关 Logical 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!