how to control the length of indexed array element?
1 view (last 30 days)
Show older comments
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 Comments
Accepted Answer
per isakson
on 10 May 2020
Edited: per isakson
on 11 May 2020
"(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 Comments
Tommy
on 11 May 2020
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
More Answers (1)
Mehmed Saad
on 10 May 2020
Edited: Mehmed Saad
on 10 May 2020
- 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 Comments
See Also
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!