Search All of the Math Forum:

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

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

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

 Messages: [ Previous | Next ]
 ryanshuell@gmail.com Posts: 150 Registered: 2/11/08
Re: obtain independent vectors of non zeros
Posted: Dec 23, 2012 9:06 PM

"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

Date Subject Author
12/17/12 diana escalona
12/23/12 ryanshuell@gmail.com
12/23/12 ryanshuell@gmail.com