How to read/print the powers from the matlab output function coeffs ?
l^4*w^3*z^1 and l^4*w^3
I would like to obtain numbers 341 and 340 from the above sequence.
[r, t] = coeffs(10*z^2*w^4 + 5*w^2*l^2 + 2*z^6)
t =
[ l^2*w^2, w^4*z^2, z^6]
% 220 402 006

 採用された回答

Ameer Hamza
Ameer Hamza 2020 年 6 月 19 日

1 投票

How are the terms separated? If separated using '+' operator, then try the following code
str = '10*z^2*w^4 + 5*w^2*l^2 + 2*z^6';
patterns = {'w\^([0-9]*)', 'l\^([0-9]*)', 'z\^([0-9]*)'};
tokens = cellfun(@(p) {regexp(strsplit(str, '+'), p, 'tokens')}, patterns);
y = cellfun(@(token) {cellfun(@helperFun, token)}, tokens);
y = reshape(cell2mat(y(:)), 1, []);
function y = helperFun(x)
if ~isempty(x)
y = str2double(x{1}{1});
else
y = 0;
end
end
Result
>> y
y =
4 0 2 2 2 0 0 0 6

3 件のコメント

Image Analyst
Image Analyst 2020 年 6 月 19 日
He said he wants "just the powers" so I assume he wants just the numbers that are powers (exponents) meaning the numbers after the carets ^.
Ameer Hamza
Ameer Hamza 2020 年 6 月 19 日
But OP mentioned for the first example that "I would like to obtain numbers 341 and 340 from the above sequence." and for the second example
[ l^2*w^2, w^4*z^2, z^6]
% 220 402 006
so I guessed that the absent variables would have 0 exponents.
Image Analyst
Image Analyst 2020 年 6 月 19 日
Oh, that could be another interpretation. I was wondering how he got those numbers. Let's hope for clarification from Ole. It seems he has totally forgotten about this question he posted.

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2020 年 6 月 18 日

1 投票

Here's one way, using isstrprop():
chr = 'l^4*w^3*z^1 and 8^4*w^3' % Create test character array.
mask = isstrprop(chr,'digit') % Get locations of numbers
caretLocations = chr == '^'
caretLocations = [false, caretLocations(1:end-1)] % Shift to the right.
mask = mask & caretLocations
chr(~mask) = ' '
numbers = sscanf(chr, ' %f')

1 件のコメント

Image Analyst
Image Analyst 2020 年 6 月 19 日
Results:
numbers =
4
3
1
4
3

サインインしてコメントする。

カテゴリ

ヘルプ センター および File Exchange で MATLAB についてさらに検索

タグ

質問済み:

Ole
2020 年 6 月 18 日

コメント済み:

2020 年 6 月 19 日

Community Treasure Hunt

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

Start Hunting!

Translated by