Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Thread Subject:
matrix addressing problem

Subject: matrix addressing problem

From: Chris

Date: 24 Nov, 2009 12:06:04

Message: 1 of 3

Hi, I'm having a simple problem addressing a matrix using row and column vectors and changing the cells in the matrix based on the vectors. It works using a single index in the find command but when using row and column, Matlab sets the whole matrix to the new value:

mask=zeros(300,400);
mask2=rand([300,400]);
[a,b]=find(mask2 < .2);
mask(a,b)=4;
pcolor(mask)

Subject: matrix addressing problem

From: ImageAnalyst

Date: 24 Nov, 2009 12:32:47

Message: 2 of 3

On Nov 24, 7:06 am, "Chris " <c.j.craws...@googlemail.com> wrote:
> Hi, I'm having a simple problem addressing a matrix using row and column vectors and changing the cells in the matrix based on the vectors. It works using a single index in the find command but when using row and column, Matlab sets the whole matrix to the new value:
>
> mask=zeros(300,400);
> mask2=rand([300,400]);
> [a,b]=find(mask2 < .2);
> mask(a,b)=4;
> pcolor(mask)

--------------------------------------------------------------------
Try this instead:

% Clean up
clc;
close all;
clear all;
workspace;

mask = zeros(300,400);
mask2 = rand(size(mask));
thresholdedArray = (mask2 < .2);
mask(thresholdedArray) = 4;
imagesc(mask);
colormap('gray');

set(gcf, 'Position', get(0, 'ScreenSize')); % Maximize figure.

Subject: matrix addressing problem

From: Jos 10584

Date: 24 Nov, 2009 12:34:05

Message: 3 of 3

"Chris " <c.j.crawshaw@googlemail.com> wrote in message <hegi7c$ng8$1@fred.mathworks.com>...
> Hi, I'm having a simple problem addressing a matrix using row and column vectors and changing the cells in the matrix based on the vectors. It works using a single index in the find command but when using row and column, Matlab sets the whole matrix to the new value:
>
> mask=zeros(300,400);
> mask2=rand([300,400]);
> [a,b]=find(mask2 < .2);
> mask(a,b)=4;
> pcolor(mask)

You need to convert subindices (row and column numbers) into linear indices. You can use SUB2IND for that

  [a,b] = find ...
  idx = sub2ind(size(mask),a,b)
  mask(idx) = ...

or, even better, let FIND return linear indices directly

  idx = find(...) % only one output argument
  mask(idx) = ...

hth
Jos

Tags for this Thread

No tags are associated with this thread.

What are tags?

A tag is like a keyword or category label associated with each thread. Tags make it easier for you to find threads of interest.

Anyone can tag a thread. Tags are public and visible to everyone.

Contact us