how to control the length of indexed array element?
1 次查看(过去 30 天)
显示 更早的评论
m=[1 2 3 4];
m_d=0.5.*ones(1,length(m));
for i=1:length(m)
m_xx=m(i)(1:(length(m(i))*m_d(1))); %error is here
end
I want to control an indexed array element length for my project and I really can't get the correct syntax for this
2 个评论
采纳的回答
per isakson
2020-5-10
编辑:per isakson
2020-5-11
"(from 1 to the last bit of m(i)) "
Here is my shot in the dark
%%
m = uint8([1,2,3,4]);
len = length(m);
m_d = 0.5*ones(1,len);
m_xx = cell(1,len);
for jj = 1 : len
m_xx{jj} = bitget( m(jj), [1:8], 'uint8' );
end
%%
m_xx{1}
m_xx{4}
outputs
ans =
1×8 uint8 row vector
1 0 0 0 0 0 0 0
>> m_xx{4}
ans =
1×8 uint8 row vector
0 0 1 0 0 0 0 0
Comments
- bitget only takes whole numbers (I chose uint8 to keep the output short)
- cannot [not meaningsful to] multiply an integer with 0.5
- I stored the result in a cell array, but there are other alternatives
In reponse to comment
Now I understand your question, I think.
Mehmed Saad have listed problems with your puzzling statement.
Your statement
m_xx = a(1:(length(a)*.5));
works because the length(a) is an even number.
Try
%%
a=[1 2 3 4];
b=[3 4 5 6];
c=[1 2 4 5];
m=[a b c]; % concatenates a, b and c into a row of length 12. That's less useful.
%%
m = { a, b, c }; % cell array. Comma is more readable than space
len = length( m );
m_xx = cell( 1, len ); % pre-allocate cell array for holding the results
for jj = 1 : length( m ) % i is the imaginary unit
m_xx{jj} = m{jj}( 1 : length(m{jj})*0.5 );
end
and
>> m_xx{:}
ans =
1 2
ans =
3 4
ans =
1 2
Comment
The statement in the for-loop looks a lot like your statement. However, you missed
- that m and m_xx need to be cell arrays and
- the difference between () and {} when using cell arrays.
3 个评论
Tommy
2020-5-11
Ah. See if this gets you where you're going:
a=[1 2 3 4];
b=[3 4 5 6];
c=[1 2 4 5];
m={a;b;c}; % a, b, and c can be different lengths
for i=1:numel(m)
m_xx=m{i}(1:end/2)
end
更多回答(1 个)
Mehmed Saad
2020-5-10
编辑:Mehmed Saad
2020-5-10
- you cannot feed 0 as array index it will give error
- for loop runs from 0 to length of m which will make it run for 5 iterations instead of 4
- m(i) will give you ith index. 1:length(m(i)) will be 1 as length(m(i)) will always be 1
- in order to access m's index from 1 to i, you have to replace all that code with m(1:i). also start for loop from 1 and not from 0
5 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Matrix Indexing 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!