Drexel dragonThe Math ForumDonate to the Math Forum



Search All of the Math Forum:

Views expressed in these public forums are not endorsed by Drexel University or The Math Forum.


Math Forum » Discussions » Software » comp.soft-sys.matlab

Topic: obtain independent vectors of non zeros
Replies: 2   Last Post: Dec 23, 2012 9:17 PM

Advanced Search

Back to Topic List Back to Topic List Jump to Tree View Jump to Tree View   Messages: [ Previous | Next ]
ryanshuell@gmail.com

Posts: 110
Registered: 2/11/08
Re: obtain independent vectors of non zeros
Posted: Dec 23, 2012 9:06 PM
  Click to see the message monospaced in plain text Plain Text   Click to reply to this topic Reply

"diana escalona" wrote in message <kaoou1$3uv$1@newscl01ah.mathworks.com>...
> How can I obtain cell array whenever I find a zero or zeros, for example:
>
> a=[16 17 32 0 0 63 79 80 0 0 0 113 0 129 130]
>
> I want to obtain subsets of non zeros and their sum
>
> a1={16 17 32 } and their sum1= sum(a1)
>
> a2={63 79 80} and their sum2= sum(a2)
>
> a3={113} and their sum3= sum(a3)
>
>
> a4={129 130 } and their sum4= sum(a4)




Something like this?
string = '16 17 32 0 0 63 79 80 0 0 0 113 0 129 130';
delimiter = '0'; % For tabs, use: delimiter = sprintf('\t');

% Find the delimiters
delimIdx = find(string == delimiter);

% Pretend there are delimiters at the beginning and end, for the loop below
delimIdx = [0 delimIdx length(string)+1];

% Preallocate cell array to hold substrings
subStrings = cell(1, length(delimIdx) - 1);

% Process each element
for i = 1:length(subStrings)

% Find the text between the delimiters
%(don't include the delimiters)
startOffset = delimIdx(i) + 1;
endOffset = delimIdx(i+1) - 1;

% Get the element
txt = string(startOffset:endOffset);

% Attempt conversion to number
num = sscanf(txt, '%f');

% Number conversion successful if no error message
if isempty(num)
subStrings{i} = txt;
else
subStrings{i} = num;
end

end



Point your RSS reader here for a feed of the latest messages in this topic.

[Privacy Policy] [Terms of Use]

© Drexel University 1994-2014. All Rights Reserved.
The Math Forum is a research and educational enterprise of the Drexel University School of Education.